Finite State Machines

The Partridge Family were neither partridges nor a family. Discuss.
Post Reply
Deme
Posts: 2
Joined: January 15th, 2013, 3:56 am

Finite State Machines

Post by Deme » February 28th, 2013, 11:59 pm

I am really running into a brick wall trying to figure out FSM design in c++ can anyone make a UTUBE video explaining.

How their design using the switch command in C++.
How they relate to the code in place.
Possibly a visual representation of the process of the FSM over Chili's Framework.

I'll put this in video game mechanic so I understand what I am saying hope fully you guys can translate
For example something simple like running a randomization of %100 that references that the random value is lower then a specific number in an array based upon a list assignment presenting a TRUE or FALSE indication. That regulates that IF TRUE = "HIT" IF FALSE = "MISS".

Then perhaps like a graphical representation of that IF "HIT"=TRUE based upon a different variable like a strength variable referenced in a different ARRAY this amount of "DAMAGE" is caused and thus a percentage of the health bar is decreased based on a specific number subtraction AND/OR a percentage of the overall contents of the floating Variable if that makes sense.

I assume almost every game engine uses a mathematical FSM to determine how much damage is caused, how much health an opponent has, how much closer to 0 health the opponent is after being successfully damage and of course applies negatives to the attackers damage dependent upon what type of armor is equipped.

If i'm way off base here I sorry just need to see that visually to understand how it works because i'm lost for some reason.

Thanks, Deme

albinopapa
Posts: 4373
Joined: February 28th, 2013, 3:23 am
Location: Oklahoma, United States

Re: Finite State Machines

Post by albinopapa » March 1st, 2013, 6:03 am

I think it depends on the type of game you are programming as far as HP or health depletion. There was an article I read that used Quake as an example. FSM was used for AI implementation such as spawning enemies and ammo as it was fired, the life cycle of the rocket for example and if in line of sight or sound, the enemy would follow the sound or follow you until you ran from line of sight for a certain amount of time then you would be considered lost.

Basically, it had more to do with the state the AI was in (idle, searching, attacking, etc). As far as coding goes, the use of classes and virtual functions seems to have something to do with it, but I haven't gotten around to using these parts of code yet sorry.
If you think paging some data from disk into RAM is slow, try paging it into a simian cerebrum over a pair of optical nerves. - gameprogrammingpatterns.com

albinopapa
Posts: 4373
Joined: February 28th, 2013, 3:23 am
Location: Oklahoma, United States

Re: Finite State Machines

Post by albinopapa » March 1st, 2013, 6:26 am

Oh, btw, in an RPG I think you have to decide things such as "attack points" "defense points" "armor defense points" "weapon attack points" and possibility of making a critical hit using a formula as simple as

Code: Select all

int damage;
int baseDef;                     //Players base defense points
int armorDef;                    //Defense points of the currently equipped armor
int weaponAtt;                 //Attack points of the currently equipped weapon
int baseAtt;                     //Players base attack points

// enemy and player would be objects of a class and a member Lvl[idnumber] would be set
// to keep track of which player and enemy is on which level.

damage = baseDef + armorDef - (weaponAtt + baseAtt) - ((enemy.Lvl[idnumber] - player.Lvl[idnumber]) * 10 );

player.HP = player.HP - damage;
I'm sure there are more complex ways of doing it there would probably be the item level and other factors to add into the formula. This however isn't an FSM.
If you think paging some data from disk into RAM is slow, try paging it into a simian cerebrum over a pair of optical nerves. - gameprogrammingpatterns.com

Deme
Posts: 2
Joined: January 15th, 2013, 3:56 am

Re: Finite State Machines

Post by Deme » March 1st, 2013, 9:18 pm

Thanks for all your feedback albinopapa the code snippet you gave me gave me and idea of where to start my programming I have found and example of an actual working simplified FSM that I assume works but I was hoping someone could help me translate what the FSM is doing the code could be used probably if you wanted to run some AI stuff. I am not sure how to post code here so i hope i do it right maybe you guys can all help me decipher what i am reading in the code. Maybe chili can dissect it for us when he gets a chance. I miss you chili. Oh i found thes FSM code on the internet somewhere.

------------------------------------------------------------------------------------------------
Header
------------------------------------------------------------------------------------------------
//FSM.h
#ifndef FSM_H
#define FSM_H

#include <iostream>
#include <string>
#include <vector>
#include <memory>

class FSM;

//An individual state (must belong to a FSM)
//This is an abstract class and must be sub-classed
class FSMState
{
public:
FSMState(){};
FSMState(FSM *fsm){};
virtual ~FSMState(){};
virtual void Update(const float& dt) = 0;
virtual void DoENTER(){};
virtual void DoEXIT(){};

std::string stateName; //used to switch between states
FSM *fsm;
};

//A vector of shared pointers housing all the states in the machine
typedef std::vector< std::tr1::shared_ptr<FSMState> > StateBank;

//---------------------------------------
//A Simple Finite State Machine
class FSM
{
public:
FSM();
~FSM();
void Update(const float& dt);

void TransitionTo(std::string stateName);
void DelayTransitionTo(std::string stateName);
void AddState(FSMState *newState, bool makeCurrent);
std::string GetState();

public:
FSMState *currentState;
std::string delayState;

//Bank to house list of states
StateBank stateBank;
std::vector< std::tr1::shared_ptr<FSMState> >::iterator iter;
};

#endif
------------------------------------------------------------------------------------------------
//CPP
------------------------------------------------------------------------------------------------
/FSM.cpp
#include "FSM.h"

//Constructor
FSM::FSM()
{
currentState = NULL;
delayState = "NONE";
}

//Destructor
FSM::~FSM()
{
stateBank.clear();
}

//Update each tick
void FSM::Update(const float& dt)
{
//Make sure a current state is loaded
if (currentState == NULL) return;

//Check if there are any delayed transition requests
if (delayState != "NONE")
{
TransitionTo(delayState);
delayState = "NONE";
}

//Update the current state, may trigger a transition.
currentState->Update(dt);
}

//Called to transition to another state
//@param stateName the name of the state to transition to
void FSM::TransitionTo(std::string stateName)
{
//Find the named state
FSMState *goToState = NULL;
for(iter= stateBank.begin(); iter!= stateBank.end(); iter++)
if ( (*iter)->stateName == stateName )
goToState = iter->get();

//Error, trying to transition to a non-existant state
if (goToState == NULL)
{
//Print an error here, or assert if you want
return;
}

currentState->DoEXIT();
goToState->DoENTER();
currentState = goToState;
}

//Transition to another state (delayed until beginning of next update)
//@param stateName the name of the state to transition to
void FSM::DelayTransitionTo(std::string stateName)
{
delayState = stateName;
}

//Add a state to the bank, optionally make it the current state
//@param newState the new state to add to the state machine
//@param makeCurrent is this new state the current state?
void FSM::AddState(FSMState *newState, bool makeCurrent)
{
//Add this state to the FSM
std::tr1::shared_ptr<FSMState> newStatePtr(newState);
stateBank.push_back(newStatePtr);
//Make this the current state?
if (makeCurrent) currentState = newState;
}

//What is the name of the current state?
std::string FSM::GetState()
{
return currentState->stateName;
}

User avatar
LuX
Posts: 1492
Joined: April 22nd, 2012, 12:33 pm
Location: Finland

Re: Finite State Machines

Post by LuX » March 2nd, 2013, 2:43 pm

Hmm... So you are asking how to make AI that works depending on a state?

It more about the "idea" than "formula" since there is no one way of doing it, and it really depends on the game type you are doing.
ʕ •ᴥ•ʔ

albinopapa
Posts: 4373
Joined: February 28th, 2013, 3:23 am
Location: Oklahoma, United States

Re: Finite State Machines

Post by albinopapa » March 5th, 2013, 4:26 am

Thanks for posting, it seems to be a pretty neat template for an FSM. This seems to iterate through a text string to match to a list of states that are stored using the vector class to store the different states and be able to add states dynamically.

It has five functions.
GetState: which retrieves the current state.
AddState: which you would use to add states to a bank or list of states using the vector class
DelayTransitionTo: which holds the state at current until Update
Update: updates the current state to the new state
TransitionTo: which does the actions set forth by the new state in this case appears to be DoENTER.

I think I got this right, but am not 100% sure.
If you think paging some data from disk into RAM is slow, try paging it into a simian cerebrum over a pair of optical nerves. - gameprogrammingpatterns.com

Post Reply