游戏逻辑底层,MainLoop&&FSM&&MSG(三)

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将所有的事件状态分为了enterexecuteexit三个基本事件,这样在游戏中的所有事件,无论是持续性的还是瞬时事件都可以用其概括。

接下来我们看一下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,意指随时可能发生的状态,比如你下班回家

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值