FSM–有限状态机
今天我们来探讨一下Finite State Machine,有限状态机,简称FSM,有兴趣的同学可以看一下《游戏编程中的人工智能》这本书,写得很经典(无论从代码上来说还是思维上来说),此次的例子基本是在此书的思想结构上来编程的。
FSM的基本思想我不多赘述,我们只关注代码的实现。
首先是State基类
State.h
template<class Type>
class State
{
public:
virtual ~State(){}
virtual void enter(Type*) = 0;
virtual void execute(Type*) = 0;
virtual void exit(Type*) = 0;
virtual bool onMsg(Type*, const Telegram&) = 0;
};
State是一个纯虚类,我们通过继承来使用它的子类,而不用State本身。
这里有一个很好的抽象,State将所有的事件状态分为了enter,execute,exit三个基本事件,这样在游戏中的所有事件,无论是持续性的还是瞬时事件都可以用其概括。
接下来我们看一下StateMachine类(!!!重要提示,文件头不要使用#ifndef宏,会出现宏冲突,请使用#pragma once)
StateMachine.h
template<class Type>
class StateMachine
{
private:
State<Type>* _currentState;
State<Type>* _previousState;
State<Type>* _globalState;
Type* _owner;
public:
StateMachine(Type*);
virtual ~StateMachine();
public:
//ignore getxx & setxx...
void update() const;
bool handleMsg(const Telegram&);
void changeState(State<Type>*);
bool isStateOn(State<Type>& state)const;
void revert2PreviousState();
};
template<class Type>
StateMachine<Type>::StateMachine(Type* owner) :_currentState(NULL),
_previousState(NULL),
_globalState(NULL),
_owner(owner)
{
}
template<class Type>
StateMachine<Type>::~StateMachine()
{
}
template<class Type>
void StateMachine<Type>::update()const
{
if (_globalState)
_globalState->execute(_owner);
if (_currentState)
_currentState->execute(_owner);
}
template<class Type>
bool StateMachine<Type>::handleMsg(const Telegram& tel)
{
if (_currentState&&_currentState->onMsg(_owner, tel))
return true;
if (_globalState&&_globalState->onMsg(_owner, tel))
return true;
return false;
}
template<class Type>
void StateMachine<Type>::changeState(State<Type>* newState)
{
assert(newState&&"a null state,tring to changeState falied");
_previousState = _currentState;
_currentState->exit(_owner);
_currentState = newState;
_currentState->enter(_owner);
}
template<class Type>
bool StateMachine<Type>::isStateOn(State<Type>& state)const
{
return typeid(*_currentState) == typeid(state);
}
template<class Type>
void StateMachine<Type>::revert2PreviousState()
{
changeState(_previousState);
}
我们看一下update函数就可以知道此类的运行方式,每次更新执行globalState,意指随时可能发生的状态,比如你下班回家