Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon


29. June 2016

 

Welcome to a new tutorial series here on GameFromScratch.com where we will be looking at core concepts of game programming.  This includes data structures, design patterns and algorithms commonly used in game development.  We start the series off with Finite State Machines.

 

There is an HD video version of this tutorial available here and embedded below.

 

What is a Finite State Machine?

 

A Finite State Machine (or FSM for short) is one of those concepts that sounds much scarier than it actually is.  In the simplest form it’s a datatype that can have only one value (state) from a finite selection of values(states).  The easiest way is to understand the finite state machine is to look at a real world example.

 

trafficLight

 

Yep, a traffic light is a perfect example of a FSM, or at least, the logic controlling it is.  Consider the three possible states this particular traffic light can be in.  At any given point (assuming I suppose the power is working...) the light will be one of three states, red, yellow or green.  It can never been more than one of those states at a time, it’s always red or yellow or green.  These are the two keep concepts of a finite state machine.  There are a finite number of states ( 3 in this case ) and only one is true or active at a time.

 

It’s a very simple concept, but extremely useful in game development.

 

What are FSMs Used For?

 

In game development, one of the most common uses for finite state machines is artificial intelligence.  Consider the example of PacMan’s ghosts.  A state machine can be used to control how they behave.  A ghost may have one of several different operating modes for example waiting to be released, hunting, hunted and dead.  The state machine is what is used to drive the ghost’s actions and to switch between states.  You will find AI examples absolutely loaded with state machines, often with some fuzzy logic controlling the transition between states to give a layer of unpredictability to your characters.

AI isn’t the only place of course, think of all the different things in a game that are related, there are multiple different states they can be in, but only one can be active at a time.  Game states are a very common example, where you break your game up into a series of states, for example Loading, Main Menu, Playing, High Score, Exiting.  Many game engines ( one such example is Phaser ) split your game up into a series of states.  The ultimate controller of these states is a finite state machine.  A sequential UI ( think of a sequence of dialogs controlled by next/back buttons ) can also be implemented using FSMs.  They are also commonly used to control elements in a games world.  Consider a game with a weather system, be it day or night cycles or season cycles like Spring, Summer, etc...  these would most likely be controlled via FSMs.

 

Implementing a Finite State Machine

 

The example we are going to use here is to implement a traffic light via FSM.  At it’s core the data is going to be stored in an enum, a natural fit for state machines, but stack based or array based options are also viable.  This example is not only going to switch the traffic lights periodically, it’s also going to implement callbacks so the world at large can interact with the light.  This example is implemented using C#, but should be easily adapted to most modern programming languages.

 

using System;

namespace GameFromScratchDemo
{

    public class TrafficLight{
        // This enum represents the three possible values our state machine can 
        be
        public enum States { Green, Yellow, Red };    
        // This is the amount of time for the timer to wait before changing 
        between states
        private const int LIGHT_DURATION = 5000;

        // An actual instance of our enum.
        private States _state;

        // The timer object that is going to be used to switch between states 
        private System.Threading.Timer _timer;

        // This function is called by the timer when it's time for a light to 
        change
        public void lightChanged(){
            System.Console.WriteLine("Light Changed");
            
            //  For each state, move to the next appropriate state.  I.e, red 
            becomes green, etc. 
            switch(_state){
                case States.Green:
                _state = States.Yellow;
                break;

                case States.Yellow:
                _state = States.Red;
                break;

                case States.Red:
                _state = States.Green;
                break;
            }

            // Reset our timer, so this will all happen again and again
            _timer.Change(LIGHT_DURATION,System.Threading.Timeout.Infinite);

            // Call our event.  This is used to communicate with the outside 
            world that our state change occured
            onStateChange(_state);
        }

        // In our constructor we simply set out default state (green) and 
        create/start our timer
        public TrafficLight() {
            _state = States.Green;
            System.Console.WriteLine("Light Created with initial Green state");

            _timer = new System.Threading.Timer( _ => lightChanged(), null, 
            LIGHT_DURATION,
                System.Threading.Timeout.Infinite);
        }

        // these two work together to provide the callback functionality
        // Implementing callback is going to differ greatly from langauge to 
        language
        public delegate void StateChangedResult(States newState);
        public event StateChangedResult onStateChange;
    }

    // Our actual program.  Simply create a traffic light instance
    // Register a callback that will simply print the current state returned 
    when the light state changes
    // And finally wait for the user to hit enter before ending the program
    public class Program
    {
        public static void Main(string[] args)
        {
            TrafficLight light = new TrafficLight();
            light.onStateChange += (TrafficLight.States state) => { Console.
            WriteLine(state); };
            Console.ReadLine();
        }
       
    }
}

The example is pretty well documented in the code above.  Essentially we are creating a class TrafficLight that can internally have one of three states Green, Yellow or Red.  It also implements a timer that switches between those states.  To make the code actually useful, it also implements a callback system so code external to the TrafficLight can interact with it as a black box.  The callback will be passed the current state value every time the light changes.

 

This is obviously a simple example of a state machine but the same basic premise remains regardless to complexity.  It is a very useful data structure for organizing code, especially the flow of logic.  Coupled with callbacks, it is also a great way of keeping systems decoupled as much as possible.

 

The Video

Programming, Design , ,

blog comments powered by Disqus

Month List

Popular Comments

GFS PlayN Installer–Super detailed installation instructions
Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon


6. November 2011

 

 

The Gamefromscratch PlayN installer is fairly straight forward in execution but has a few tricky points.  Also, I can’t be sure it will work 100% and you can refer to this process to see if your installation worked properly.

 

 

On occasion an environmental or Maven problem can occur during installation, or you weren’t fast enough installing the Android SDK.  If that happens, simply close the dos prompt then run the installer again.

 

 

First things first, download the GFSPlayNInstaller.  Extract this file anywhere on your computer, it will contain two files, a .CMD and at .PS1 file.  The PS1 file does all the work, but needs to be launched using the .CMD to have the proper permissions.  Do not run from within the zip, this will not work.  Throughout the install you might get a Windows firewall prompt regarding Java, this is part of the Google PlayN install process and should be granted permission.

 

 

Double click Install.cmd

 

 

A command prompt will open and you will receive a prompt to determine if your system is 32 or 64 bit; hopefully the detection is correct and you can simply click YES.

 

1

 

 

 

Now you will be prompted if you have a Java JDK installed ( the JRE is not enough! ).

 

2

 

 

 

If you do not have a JDK installed or you do not know, click No.  This will cause the JDK to be downloaded and installed automatically.  If you already have a JDK installed click Yes, and the following dialog will appear:

 

3

 

 

 

Simply navigate to the JDK directory and click OK.  Do NOT click cancel, I am not completely sure what will happen, but I doubt it’s good. Winking smile  If you clicked No earlier, you will not get this dialog.  If you clicked YES and the dialog didn’t appear, alt-tab around to see if it is there somewhere, it doesn’t always get focus.

 

 

Now you will be presented with this dialog:

 

4

 

 

 

This dialog is determining where PlayN is going to be installed.  If you simply click OK, it will be created in C:\.  Where ever you select a new folder PlayN will be created, so you do not need to create a folder just for it.  Again, don’t click Cancel…  Now the installer is going to go off and do its magic for a while….

 

5

 

 

 

Behind the scenes it is doing a number of things, downloading a zip program, grabbing Git and the Android SDK.  Even if you don’t want to develop for Android, you need the SDK installed for PlayN to work properly.  That is the next step and it is very important you do this part correctly as it was the only bit I could not automate!  You need to configure the Android SDK and you need to do it fairly quickly as the install will continue while the Android SDK install happens and eventually the install is going to depend on the SDK being installed.  Worst case scenario, run the installer again and simply close the Android SDK window when it opens.

 

 

 

As I said, this part is important, so I made a rather cryptic message box to inform you of just that!

 

 

6

 

 

 

Once you click OK, the race is on!  The Android SDK installer will be loaded and it should look like this:

 

7

 

 

 

It will take a minute or two to configure all of the various options… don’t be distracted by the installer going on in the background, keep your attention focused here!  First things first, once it’s done fetching info, click the “Deselect All” button to clear all selections.  Then you want to select Android 3 ( API11 )->SDK Platform, like this:

 

 

8

 

 

 

If everything was done correctly, the button will show “Install 1 package…”.  If you want more features, you can run the Android SDK Manager later… when you aren’t under type restraints! Winking smile

 

After you click the Install 1 package… button, you will see:

 

9

 

 

Simply click Install.

 

 

Alright, stressful bits are over, now just a matter of sitting back and letting the installer do it’s thing..

 

 

10

 

 

 

That was a screenshot of the installer doing it’s thing.  Frankly it isnt very exciting and yes, it’s a rather long process.  While that process is happening, the Android SDK Manager is chugging along and will eventually say:

 

11

 

 

Say whatever you want, it doesn’t really matter so you might as well go with Yes.  Eventually assuming success with the Maven process ( actually it runs even if there is a failure… if you see a whole bunch of failures, try running the installer again ), you will get the following prompt:

 

 

12

 

 

 

This is just another simple GFS provide script that builds your new game Maven script for you.  If you want to create a game of your own, click Yes.  If you click Yes…

 

13

 

 

The new game wizard will appear!  Simply fill in the values you want to make your game, like I have above and click Make Game!  Once you click “Make Game” a MakeGame.bat file will be created then run.  This process creates an actual game within your PlayN folder.  Unfortunately I couldn’t completely automated it and it will prompt you to continue.  When prompted ( in the dos prompt ) type Y then [Enter].  Voila, your new game is created!  If you chose C:\ for your PlayN folder, your game will be located at [C:\PlayN\PlayN\YourGame]

 

 

Finally, you will get one last prompt:

 

14

 

 

I hear there are all kinds of interesting things at that website, you should click Yes and check it out! Winking smile  If you click Yes, it will open your webbrowser ( or a new tab if already open ) and send you to GameFromScratch.com.

 

 

 

Voila, all done!  Enjoy PlayN!

 

 

If you want to create a new game at a later date, the New Game Wizard can be run again, it is located at Playn\Playn\NewGame.cmd.

 

 

If you encounter any problems, please let me know and I will do what I can.  Either use comments here, send me an email ( not preferred, because other people having the sample problem will not benefit from the results ) or I will piggyback the PlayN teams support process and request you post to StackOverflow with the PlayN tag and I will keep an eye on posts there.

General

blog comments powered by Disqus

Month List

Popular Comments