cocos2d-x 遊戲開發之有限狀態機器(FSM) (四),cocos2d-xfsm

來源:互聯網
上載者:User

cocos2d-x 遊戲開發之有限狀態機器(FSM) (四),cocos2d-xfsm
cocos2d-x 遊戲開發之有限狀態機器(FSM) (四)

雖然我們瞭解了FSM,並且可以寫自己的FSM,但是有更好的工具幫我們完成這個繁瑣的工作。SMC(http://smc.sourceforge.net/)就是這樣的工具。:

http://sourceforge.net/projects/smc/files/latest/download

在bin下面的Smc.jar是用於產生狀態類的命令列工具。使用如下命令:

$ java -jar Smc.jar Monkey.sm

1 真實世界的FSM

首先定義一個狀態機器純文字檔案:Monkey.sm,內容如下:

// cheungmine// 2015-01-22// entity class%class Monkey// entity class header%header Monkey.h// inital state%start MonkeyMap::STOP// entity state map%map MonkeyMap%%STOPEntry {stop();}Exit {exit();}{walk WALK {}}WALKEntry {walk();}Exit {exit();}{stop STOP {}turn TURN {}}TURNEntry {turn();}Exit {exit();}{walk WALK {}}%%

其中%class Monkey 說明實體類的名字:Monkey (Monkey.h和Monkey.cpp)

%header 指定標頭檔:Monkey.h

%map 指明狀態圖類,這個類包含全部狀態。這裡是:MonkeyMap

%start 指明其實的狀態,這裡是STOP,對應的類是:MonkeyMap_STOP

%%...%%之間的部分定義每個狀態。格式如下:

STOP    // 狀態名Entry {    // 執行這個函數進入該狀態    stop();}Exit {    // 執行這個函數退出該狀態    exit();}{    // 狀態切換邏輯    walk WALK {}}

當運行下面的命令,會自動組建檔案:Monkey_sm.h和Monkey_sm.cpp。連同內建的statemap.h一起加入到項目中。
java -jar Smc.jar Monkey.sm

2 實體類

商務邏輯仍然要我們自己實現,那就是寫Monkey.h和Monkey.cpp。不過這次寫Monkey類需要按一定的規則,下面是原始碼:

// Monkey.h//#ifndef MONKEY_H_#define MONKEY_H_#include "cocos2d.h"USING_NS_CC;#include "Monkey_sm.h"#define MAX_STOP_TIME  3#define MAX_WALK_TIME  10#define MAX_WALK_DIST  200class Monkey : public Node{public:    CREATE_FUNC(Monkey);    virtual bool init();    void stop();    void walk();    void turn();    void exit();private:    MonkeyContext * _fsm;    int    _step;    int    _curPos;    time_t _curTime;    // Sprite * _sprite;private:    void onIdleStop(float dt)    {        int d = (int) (time(0) - _curTime);        if (d > MAX_STOP_TIME) {            _fsm->walk();        }    }    void onIdleWalk(float dt)    {        if (_curPos > MAX_WALK_DIST || _curPos < -MAX_WALK_DIST) {            _fsm->turn();        }        int d = (int) (time(0) - _curTime);        if (d > MAX_WALK_TIME) {            _fsm->stop();        }        _curPos += _step;    }    void onIdleTurn(float dt)    {        _fsm->walk();    }};#endif // MONKEY_H_

上面的onIdle????是觸發狀態的回呼函數,實體狀態改變的商務邏輯在這裡實現。


// Monkey.cpp//#include "Monkey.h"#include <time.h>#include <assert.h>void Monkey::exit(){    this->unscheduleAllCallbacks();    cocos2d::log("exit()");}bool Monkey::init(){    _step = 1;    _curPos = 0;    _curTime = time(0);    // _sprite = Sprite::create("monkey.png");    // addChild(_sprite);    _fsm = new MonkeyContext(*this);    assert(_fsm);    _fsm->setDebugFlag(true);    _fsm->enterStartState();    return true;}void Monkey::stop(){    _curTime = time(0);    cocos2d::log("stop(): pos=%d", _curPos);    this->schedule(schedule_selector(Monkey::onIdleStop), 0.1f);}void Monkey::walk(){    _curTime = time(0);    cocos2d::log("walk(): pos=%d", _curPos);    this->schedule(schedule_selector(Monkey::onIdleWalk), 0.1f);}void Monkey::turn(){    _step *= -1;    cocos2d::log("turn(): step=%d", _step);    this->schedule(schedule_selector(Monkey::onIdleTurn), 0.1f);      }

3 狀態機器類

架構代碼Smc已經幫我們產生好了:Monkey_sm.h和Monkey_sm.cpp:

//// ex: set ro:// DO NOT EDIT.// generated by smc (http://smc.sourceforge.net/)// from file : Monkey.sm//#ifndef MONKEY_SM_H#define MONKEY_SM_H#define SMC_USES_IOSTREAMS#include "statemap.h"// Forward declarations.class MonkeyMap;class MonkeyMap_STOP;class MonkeyMap_WALK;class MonkeyMap_TURN;class MonkeyMap_Default;class MonkeyState;class MonkeyContext;class Monkey;class MonkeyState :    public statemap::State{public:    MonkeyState(const char * const name, const int stateId)    : statemap::State(name, stateId)    {};    virtual void Entry(MonkeyContext&) {};    virtual void Exit(MonkeyContext&) {};    virtual void stop(MonkeyContext& context);    virtual void turn(MonkeyContext& context);    virtual void walk(MonkeyContext& context);protected:    virtual void Default(MonkeyContext& context);};class MonkeyMap{public:    static MonkeyMap_STOP STOP;    static MonkeyMap_WALK WALK;    static MonkeyMap_TURN TURN;};class MonkeyMap_Default :    public MonkeyState{public:    MonkeyMap_Default(const char * const name, const int stateId)    : MonkeyState(name, stateId)    {};};class MonkeyMap_STOP :    public MonkeyMap_Default{public:    MonkeyMap_STOP(const char * const name, const int stateId)    : MonkeyMap_Default(name, stateId)    {};    virtual void Entry(MonkeyContext&);    virtual void Exit(MonkeyContext&);    virtual void walk(MonkeyContext& context);};class MonkeyMap_WALK :    public MonkeyMap_Default{public:    MonkeyMap_WALK(const char * const name, const int stateId)    : MonkeyMap_Default(name, stateId)    {};    virtual void Entry(MonkeyContext&);    virtual void Exit(MonkeyContext&);    virtual void stop(MonkeyContext& context);    virtual void turn(MonkeyContext& context);};class MonkeyMap_TURN :    public MonkeyMap_Default{public:    MonkeyMap_TURN(const char * const name, const int stateId)    : MonkeyMap_Default(name, stateId)    {};    virtual void Entry(MonkeyContext&);    virtual void Exit(MonkeyContext&);    virtual void walk(MonkeyContext& context);};class MonkeyContext :    public statemap::FSMContext{public:    explicit MonkeyContext(Monkey& owner)    : FSMContext(MonkeyMap::STOP),      _owner(&owner)    {};    MonkeyContext(Monkey& owner, const statemap::State& state)    : FSMContext(state),      _owner(&owner)    {};    virtual void enterStartState()    {        getState().Entry(*this);    }    inline Monkey& getOwner()    {        return *_owner;    };    inline MonkeyState& getState()    {        if (_state == NULL)        {            throw statemap::StateUndefinedException();        }        return dynamic_cast<MonkeyState&>(*_state);    };    inline void stop()    {        getState().stop(*this);    };    inline void turn()    {        getState().turn(*this);    };    inline void walk()    {        getState().walk(*this);    };private:    Monkey* _owner;};#endif // MONKEY_SM_H//// Local variables://  buffer-read-only: t// End://

//// ex: set ro:// DO NOT EDIT.// generated by smc (http://smc.sourceforge.net/)// from file : Monkey.sm//#include "Monkey.h"#include "Monkey_sm.h"using namespace statemap;// Static class declarations.MonkeyMap_STOP MonkeyMap::STOP("MonkeyMap::STOP", 0);MonkeyMap_WALK MonkeyMap::WALK("MonkeyMap::WALK", 1);MonkeyMap_TURN MonkeyMap::TURN("MonkeyMap::TURN", 2);void MonkeyState::stop(MonkeyContext& context){    Default(context);}void MonkeyState::turn(MonkeyContext& context){    Default(context);}void MonkeyState::walk(MonkeyContext& context){    Default(context);}void MonkeyState::Default(MonkeyContext& context){    throw (        TransitionUndefinedException(            context.getState().getName(),            context.getTransition()));}void MonkeyMap_STOP::Entry(MonkeyContext& context){    Monkey& ctxt = context.getOwner();    ctxt.stop();}void MonkeyMap_STOP::Exit(MonkeyContext& context){    Monkey& ctxt = context.getOwner();    ctxt.exit();}void MonkeyMap_STOP::walk(MonkeyContext& context){    context.getState().Exit(context);    context.setState(MonkeyMap::WALK);    context.getState().Entry(context);}void MonkeyMap_WALK::Entry(MonkeyContext& context){    Monkey& ctxt = context.getOwner();    ctxt.walk();}void MonkeyMap_WALK::Exit(MonkeyContext& context){    Monkey& ctxt = context.getOwner();    ctxt.exit();}void MonkeyMap_WALK::stop(MonkeyContext& context){    context.getState().Exit(context);    context.setState(MonkeyMap::STOP);    context.getState().Entry(context);}void MonkeyMap_WALK::turn(MonkeyContext& context){    context.getState().Exit(context);    context.setState(MonkeyMap::TURN);    context.getState().Entry(context);}void MonkeyMap_TURN::Entry(MonkeyContext& context){    Monkey& ctxt = context.getOwner();    ctxt.turn();}void MonkeyMap_TURN::Exit(MonkeyContext& context){    Monkey& ctxt = context.getOwner();    ctxt.exit();}void MonkeyMap_TURN::walk(MonkeyContext& context){    context.getState().Exit(context);    context.setState(MonkeyMap::WALK);    context.getState().Entry(context);}//// Local variables://  buffer-read-only: t// End://

4 總結

FSM是一種固定的範式,因此採用工具幫我們實現可以減少犯錯誤的機會。輸入的檔案就是:實體.sm。我們把重點放在商務邏輯上,所以與狀態有關的代碼smc都幫我們產生好了。對比一下我們手工建立和smc架構工具自動產生的類:


在cocos2d-x中使用很簡單:

bool HelloWorld::init(){    //////////////////////////////    // 1. super init first    if ( !Layer::init() )    {        return false;    }        auto rootNode = CSLoader::createNode("MainScene.csb");    addChild(rootNode);    auto closeItem = static_cast<ui::Button*>(rootNode->getChildByName("Button_1"));    closeItem->addTouchEventListener(CC_CALLBACK_1(HelloWorld::menuCloseCallback, this));    /////////////////// test ///////////////////////    Monkey * mk = Monkey::create();    addChild(mk);    return true;}

就這樣了!不明白的地方請仔細閱讀:

Cocos2d-x遊戲開發之旅(鐘迪龍)






聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.