当前位置:编程学习 > C/C++ >>

一个简单确有用的有限状态机(FSM) in c++

我写了一个有限状态机的模板,因为我要写不同的FSM
 
1.状态用枚举来代替(便于调试)
 
2.要运行FSM,只需要setState和updateState(float delta_time)即可
 
3.用GetState来获取当前状态
 
4.许多转换都基于定时,因此我实现了方法GetTimeInCurState()
 
5.执行具体的action在这些方法内BeginState EndState UpdateState
 
 
[cpp] 
// (c) Francois Guibert, www.frozax.com (@Frozax)   
#pragma once   
  
template<typename T>  
class fgFSM  
{  
public:  
  fgFSM() : _time_in_cur_state(0.0f), _cur_state(-1)  
  {  
  }  
  
  virtual void BeginState( T state ) {}  
  virtual void UpdateState( T state ) {}  
  virtual void EndState( T state ) {}  
  
  void SetState( T state )  
  {  
    EndState( (T)_cur_state );  
    _cur_state = state;  
    _time_in_cur_state = 0.0f;  
    BeginState( (T)_cur_state );  
  }  
  
  void UpdateFSM( float delta_time )  
  {  
    if( _cur_state != -1 )  
    {  
      _time_in_cur_state+=delta_time;  
      UpdateState( (T)_cur_state );  
    }  
  }  
  
  float GetTimeInCurState() { return _time_in_cur_state; }  
  T GetState() { return (T)_cur_state; }  
  
private:  
  float _time_in_cur_state;  
  int _cur_state;  
};  
 
// (c) Francois Guibert, www.frozax.com (@Frozax)
#pragma once
 
template<typename T>
class fgFSM
{
public:
  fgFSM() : _time_in_cur_state(0.0f), _cur_state(-1)
  {
  }
 
  virtual void BeginState( T state ) {}
  virtual void UpdateState( T state ) {}
  virtual void EndState( T state ) {}
 
  void SetState( T state )
  {
    EndState( (T)_cur_state );
    _cur_state = state;
    _time_in_cur_state = 0.0f;
    BeginState( (T)_cur_state );
  }
 
  void UpdateFSM( float delta_time )
  {
    if( _cur_state != -1 )
    {
      _time_in_cur_state+=delta_time;
      UpdateState( (T)_cur_state );
    }
  }
 
  float GetTimeInCurState() { return _time_in_cur_state; }
  T GetState() { return (T)_cur_state; }
 
private:
  float _time_in_cur_state;
  int _cur_state;
};
用法:
 
先建立需要应用到的状态枚举,比如
 
 
[cpp] 
enum EState  
{  
  STT_OFF = -1, // optional, -1 is the initial state of the fsm   
  STT_WALK,  
  STT_RUN,  
  STT_STOP,  
  STT_EAT  
};  
 
enum EState
{
  STT_OFF = -1, // optional, -1 is the initial state of the fsm
  STT_WALK,
  STT_RUN,
  STT_STOP,
  STT_EAT
};
然后继承class fgFSM
 
 
[cpp] 
class ObjectUsingFSM: public fgFSM<EState>  
{  
public:  
  // ...   
  void UpdateState( EState t );  
  void BeginState( EState t );  
  void EndState( EState t );  
  // ...   
};  
 
class ObjectUsingFSM: public fgFSM<EState>
{
public:
  // ...
  void UpdateState( EState t );
  void BeginState( EState t );
  void EndState( EState t );
  // ...
};
该机,结束语:
 
你可以在你的项目当中免费使用这些代码,这是非常简单又常用的,另外你可以在以后根据需要在在EndState()里面加入GetPrviousState()
 
GetNextState()等等。。。
 
补充:软件开发 , C++ ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,