• 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
    11
  • comments
    17
  • views
    20631

State Machines in Games

Sign in to follow this  
Followers 0
frob

1611 views

In Part 1 we learned what state machines are and we also hard-coded a simple state machine using a switch statement.

In Part 2 we made a simple state machine interface and a generic state machine runner. We also created one boring state machine instance.

Now in Part 3 we are going to actually make a game. It isn't much of a game, but it has all the elements of gameplay. It has risk. It has danger. It has a way to win.

Okay, it is just navigating a maze of rooms in a text adventure. There are no monsters, no inventory, and no plot (we'll add all those later). For now we can just navigate a castle full of rooms.

We won't modify the state machine interface or the state machine runner that we made in part 2. They work just fine for our purposes right now.

The States of the Game

Just like the boring state machine, each state implements the IState interface and also contains some useful information specific to that state machine implementation.

The 'useful information' is a name of the room, a description of the room, and links to the neighboring rooms. The name and description are set by the constructor and the neighbors are added by the state machine when it builds the graph.

The run function actually does something this time: It writes out the description of the room as written by the constructor.

On to the code!class FunMachineState : IState { string mName; string mDescription; List mNeighbors = new List(); public List Neighbors { get { return mNeighbors; } } /// /// Initializes a new instance of the FunnerState class. /// /// Name to display for this state /// Text to display for this state public FunMachineState(string mName, string mDescription) { this.mName = mName; this.mDescription = mDescription; } #region IState Overrides public override string GetName() { return mName; } public override void Run() { // We don't do any fancy stuff, just print out where we are Console.WriteLine(); Console.WriteLine(mDescription); } #endregion }

That wasn't too bad, was it?

Most of the State Machine

Now comes the time to describe the state machine implementation.

This one gets to be a little more interesting.

I'm going to include everything in the short listing EXCEPT the state machine constructor. I'll go over that in detail in the next section.

It implements the generic IStateMachine interface and that is pretty simple.

It also adds three machine-specific values: A list of states, a link to the current state, and a link to the exit state (which we'll get rid of in the next lesson).

You might have realized this already, but each state represents a room in the map. Hopefully that was already clear, but if not I figured I should point that out.

Of special note is how it gets the list of possible transitions and how it advances. We look at the names of the current node's neighbors -- in this case is the name of a room on the map. We advance by making sure we can only travel to neighboring rooms. That avoids the exploit of typing in "move Exit" and winning the game in the first step. class FunMachine : IStateMachine { List mStates; FunMachineState mCurrent; FunMachineState mExit; /// CONSTRUCTOR NOT SHOWN #region IStateMachine Overrides public override IState CurrentState { get { return mCurrent; } } public override string[] PossibleTransitions() { List result = new List(); foreach (FunMachineState state in mCurrent.Neighbors) { result.Add(state.GetName()); } return result.ToArray(); } public override bool Advance(string nextState) { foreach (FunMachineState state in mCurrent.Neighbors) { if (nextState == state.GetName()) { mCurrent = state; return true; } } System.Console.WriteLine("Invalid state."); return false; } public override bool IsComplete() { return mCurrent == mExit; } #endregion }

Again, this is mostly straightforward. We've got our game state machine in just a few lines of code.

On to the Game's State Machine Constructor...

Here is where the fun is.

This state machine is also hard coded. In order to generate the game's maze we'll need to manually construct each room (aka FSM state, or vertex, or node). And we'll need to construct each transition (aka edge) of the state machine. public FunMachine() { // Create all the fun states in our mini-world FunMachineState entryHall = new FunMachineState("Grand Entrance", "You are standing in a grand entrance of a castle.\nThere are tables and chairs, but nothing you can interact with."); FunMachineState staircase = new FunMachineState("Grand Staircase", "The staircase is made from beautiful granite."); FunMachineState eastWing = new FunMachineState("East Wing", "This wing is devoted to bedrooms."); FunMachineState westWing = new FunMachineState("West Wing", "This wing is devoted to business."); FunMachineState bedroomA = new FunMachineState("Master Suite", "This is the master suite. What a fancy room."); FunMachineState bedroomB = new FunMachineState("Prince Bob's Room", "The prince has an extensive library on his wall.\nHe also has more clothes than most males know what to do with."); FunMachineState bedroomC = new FunMachineState("Princess Alice's Room", "The princess has filled her room with a small compur lab.\nShe spends her days playing games and writing code."); FunMachineState workroomA = new FunMachineState("Study", "This is the study. It has many books."); FunMachineState workroomB = new FunMachineState("Bathroom", "Every home needs one"); FunMachineState workroomC = new FunMachineState("Do Not Enter", "I warned you not to enter.\nYou are in a maze of twisty little passages, all alike."); FunMachineState passage = new FunMachineState("Twisty Passage", "You are in a maze of twisty little passages, all alike"); mExit = new FunMachineState("Outside", "You have successfully exited the castle."); // Hook up doors. entryHall.Neighbors.Add(staircase); entryHall.Neighbors.Add(mExit); staircase.Neighbors.Add(eastWing); staircase.Neighbors.Add(westWing); staircase.Neighbors.Add(entryHall); eastWing.Neighbors.Add(bedroomA); eastWing.Neighbors.Add(bedroomB); eastWing.Neighbors.Add(bedroomC); eastWing.Neighbors.Add(staircase); bedroomA.Neighbors.Add(eastWing); bedroomB.Neighbors.Add(eastWing); bedroomC.Neighbors.Add(eastWing); westWing.Neighbors.Add(workroomA); westWing.Neighbors.Add(workroomB); westWing.Neighbors.Add(workroomC); workroomA.Neighbors.Add(westWing); workroomB.Neighbors.Add(westWing); // Trap of doom. workroomC.Neighbors.Add(passage); passage.Neighbors.Add(passage); // Add them to the collection mStates = new List(); mStates.Add(entryHall); mStates.Add(staircase); mStates.Add(eastWing); mStates.Add(westWing); mStates.Add(bedroomA); mStates.Add(bedroomB); mStates.Add(bedroomC); mStates.Add(workroomA); mStates.Add(workroomB); mStates.Add(workroomC); mStates.Add(passage); mStates.Add(mExit); // Finally set my starting point mCurrent = entryHall; }
This creates a fun little graph.

In case you're having trouble visualizing it, the picture version looks like this:

FSM_SimpleMap.PNG

It has a few rooms with their descriptions. It has a death trap room, and it has a route to victory.

It looks like a game!

It isn't much of a maze but that's all I wanted to hard code right now.

Run the Sample Code

Now is the time to actually see the game start to come together. If you haven't downloaded the source code already from the first two samples, you can download it at the bottom of this article.

Just run the project.

When you run it you can hit "1" for the boring state machine we had in Part 2. It is boring but it works.

Much more interesting is to hit "2" for this funner state machine. Navigate the map. Get lost in the death trap (and manually close the window or Ctrl+C out of the app because there is no way out).

And you can hit "3" to see a preview of what is coming.

Always Leave Them Wanting More

So now we're done with Part 3. We have made a minimal game with state machines.

Sure the game has no items to manipulate, or plot, but that will all come later. Also to come later are other uses for state machines, such as for AI systems.

Now I'm getting ahead of myself.

If you hit "3" in the sample code (I know you did) you have had your preview to Part 4 - making your state machine data driven.

Why make it data driven? You weren't seriously thinking of hard coding a large complex dungeon into your game, were you?

[sharedmedia=core:attachments:14149]

2
Sign in to follow this  
Followers 0


0 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