• Advertisement
  • entries
    11
  • comments
    17
  • views
    21015

State Machines in Games

Sign in to follow this  

1588 views

We completed Part 1 with a simple boring hard-coded state machine, implemented by a switch statement.

It didn't do much. In textbooks that would be called "an exercise for the reader."

In this entry (Part 2) we're going to prepare the rest of the way for our game. Since I know in advance where I am leading you, I'll tell you that we need a bunch of state machines.

As this is going to become a collection of state machines, we'll extend it out into a common interface.

Programming to an interface, also called the Dependency Inversion Principle, allows us to extend a simple state machine into many different types of machines.

The Interface

Here are the two interface classes used in all the examples.public abstract class IStateMachine{ // Accessor to look at the current state. public abstract IState CurrentState { get; } // List of all possible transitions we can make from this current state. public abstract string[] PossibleTransitions(); // Advance to a named state, returning true on success. public abstract bool Advance(string nextState); // Is this state a "completion" state. Are we there yet? public abstract bool IsComplete();}public abstract class IState{ // Utility function to help us display useful things public abstract string GetName(); // Do something public abstract void Run(); // This isn't really needed, but it helps in debugging and other tasks. // It allows hover-tips and debug info to show me the name of the state // rather than the default of the type of the object public override string ToString() { return GetName(); }}


That's it for our interface.

The State Machine Runner

Now that we have the interface we can start using it.

One of the beauties of using interfaces ("Dependency Inversion Pattern") is that we can start writing our state machine without any other details.

So here is the app I wrote. Again I didn't actually implement any of the state machines for this state machine runner. I just used the interfaces:static void Main(string[] args){ // First we need to create the state machine. // Note that I'm using the abstract IStateMachine instead of a concrete class. IStateMachine machine = GetMachine(); // We have a machine, now run it. while(!machine.IsComplete()) { // Print out our current state Console.WriteLine("Currently in " + machine.CurrentState); machine.CurrentState.Run(); // Print out our possible transitions Console.WriteLine("\nAvailable choices are:"); string[] transitions = machine.PossibleTransitions(); foreach (string item in transitions) { Console.WriteLine(" " + item); } // Request a transition from the user Console.WriteLine("\nWhat do you want to do?"); string nextState = Console.ReadLine(); machine.Advance(nextState); } // And we're done! // Run our final node as a special case since the above loop won't do it. Console.WriteLine("Currently in " + machine.CurrentState); machine.CurrentState.Run(); // Finish off. Console.WriteLine("\n\nPress any key to continue."); Console.ReadKey(true);}
That's it! 36 lines of code and our game runner is finished.

What?! The game runner is finished?

That little beauty will run any state machine that implements the interface. And our little game can fit into that interface. So let's get on to filling in those pesky details.

Let's try it out with a traditional textbook state machine. I'm talking about how textbooks use labels like 0, 1, 2, and variables like x, y, and z, that carry no real useful information.

Boring State Machine Implementation

There are two major options when it comes to state machines. You can make the machine know about traversing the machine, or you can make the state know about it. It's just like in graphics how you can either have objects move around the world or you can have the world move around objects. Either way, the result is the same.

In this boring example I made a single state and made the state modify itself as the machine moved around it.

Boring Machine Sourceclass BoringMachine : IStateMachine{ BoringMachineState mState = new BoringMachineState(); public override IState CurrentState { get { return mState; } } public override string[] PossibleTransitions() { // For this simple example, forward it on to the state return mState.ListTransitions(); } public override bool Advance(string nextState) { Console.WriteLine("I'm a boring state machine. I don't care what you entered. Advancing state."); return mState.Advance(); } public override bool IsComplete() { // For the simple example, forward it on to the state return mState.IsComplete(); }}
Because it is a boring example I've simply ignored the name of the state transition. We don't need it, we simply tell the state that it is time to move on.

Boring Machine State code

Here it is, in all it's boring detail:class BoringMachineState : IState{ #region Members internal enum SameOldStates { Enter, DoStuff, Exiting, Done } SameOldStates mState = SameOldStates.Enter; #endregion #region IState overrides public override string GetName() { return mState.ToString(); } public override void Run() { // Do nothing. This is the game logic. } #endregion #region Helper functions public bool IsComplete() { return mState == SameOldStates.Done; } public string[] ListTransitions() { List result = new List(); switch (mState) { case SameOldStates.Enter: result.Add("DoStuff"); break; case SameOldStates.DoStuff: result.Add("Exiting"); break; case SameOldStates.Exiting: result.Add("Done"); break; case SameOldStates.Done: result.Add("Done"); break; } return result.ToArray(); } public bool Advance() { switch (mState) { case SameOldStates.Enter: mState = SameOldStates.DoStuff; break; case SameOldStates.DoStuff: mState = SameOldStates.Exiting; break; case SameOldStates.Exiting: mState = SameOldStates.Done; break; case SameOldStates.Done: // Do nothing. break; } return true; } #endregion}
It is a little boring. Everything is hard coded. It doesn't look like a game. It ignores user input.

But when I run it, IT WORKS!

And that's what matters.

Always Leave Them Wanting More

Okay, my game really is close to being finished.

The game runner is complete. It works perfectly for the game we're trying to make.

In part three, I'll create a second implementation of IStateMachine and IState that make an actual interactive game.

(Okay, part 3 isn't an actual FUN game, but it is enough to technically be a text adventure. That is for a very loose definition of 'adventure'.)

You can download the code in the link below. Just like before it has a preview of what is to come.

[sharedmedia=core:attachments:14149]
Sign in to follow this  


0 Comments


Recommended Comments

There are no comments to display.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Advertisement