enum EState{ eState_Min, // 未初始化状态 eState_One, eState_Two, ... eState_Max, // 用于异常检测 };
EState curState = eState_Min;
void update(){ switch(curState){ case eState_One: onStateOne(); break; case eState_Min: onStateTwo(); break; ... case eState_Max: break; default: // 报错 } }
void onStateOne(){ } void onStateTwo(){ } ...
void converToState(EState dstState){ curState = dstState; }
class BaseState{ public: virtual ~BaseState() = 0; virtual void execute() = 0; BaseState::~BaseState(){} };
class FSM{ public: void converToState(BaseState *state){ if state then delete m_curState; m_curState = NULL; end m_curState = state; } void update(){ m_curState->onState() } protected: BaseState* m_curState; };
class Monster{ public: void update(){ m_SFM->update() } protected: FSM* m_SFM; };
class StateMove:BaseState{ public: ~BaseState(){} void execute(){ // move,check } }; class StateFight:BaseState{ public: ~BaseState(){} void execute(){ // fight,check } };
原文地址:http://blog.csdn.net/xufeng0991/article/details/40746473