• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
  • entries
  • comments
  • views

State Machines in Games

Sign in to follow this  
Followers 0


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.


Sign in to follow this  
Followers 0


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