2018-07-24状态机

class StateIdle : public State
{
【2018-07-24状态机】public:
StateIdle(FSM* fsm) : State(fsm) {}
int test_counter = 0;
void OnStateEnter() {
cout << "---- Idle Enter" << endl;
test_counter = 0;
}
void OnStateTick() {
cout << "Idle Tick" << endl;
// 模拟一个定时状态转移。在实际工程中是根据需求逻辑写的
test_counter++;
if (test_counter == 5)
{
fsm->Trans(State_Attack);
}
}
void OnStateExit() { cout << "==== Idle Exit" << endl; }
};
class StateAttack : public State
{
public:
StateAttack(FSM* fsm) : State(fsm) {}
void OnStateEnter() { cout << "---- Attack Enter" << endl; }
void OnStateTick() { cout << "Attack Tick" << endl; }
void OnStateExit() { cout << "==== Attack Exit" << endl; }
};
class StateGoHome : public State
{
public:
StateGoHome(FSM* fsm) : State(fsm) {}
void OnStateEnter() { cout << "---- GoHome Enter" << endl; }
void OnStateTick() { cout << "GoHome Tick" << endl; }
void OnStateExit() { cout << "==== GoHome Exit" << endl; }
};
int main()
{
// 构造状态机
FSM* fsm = new FSM();
State* stateIdle = new StateIdle(fsm);
State* stateAttack = new StateAttack(fsm);
State* stateGoHome = new StateGoHome(fsm);
fsm->Register(State_Idle, stateIdle);
fsm->Register(State_Attack, stateAttack);
fsm->Register(State_GoHome, stateGoHome);
fsm->SetInitState(State_Idle);
// 将状态机Tick放入程序主循环中, 仅示范
while (true)
{
fsm->Tick();
sleep(1);
}
return 0;
}

    推荐阅读