首页 > 代码库 > 13--游戏存档

13--游戏存档

          保存游戏中的数据时游戏中常用的功能,Cocos2DX为我们提供CCUserDefault类。该类使用xml文件存储数据,并提供几个基本类型的存储接口。

//根据key获取指定的值,重载版本在没有读取到值返回的默认值    bool    getBoolForKey(const char* pKey);    bool    getBoolForKey(const char* pKey, bool defaultValue);        int     getIntegerForKey(const char* pKey);    int     getIntegerForKey(const char* pKey, int defaultValue);        float    getFloatForKey(const char* pKey);    float    getFloatForKey(const char* pKey, float defaultValue);      double  getDoubleForKey(const char* pKey);    double  getDoubleForKey(const char* pKey, double defaultValue);       std::string getStringForKey(const char* pKey);    std::string getStringForKey(const char* pKey, const std::string & defaultValue);    // 根据key设置值    void    setBoolForKey(const char* pKey, bool value);       void    setIntegerForKey(const char* pKey, int value);        void    setFloatForKey(const char* pKey, float value);       void    setDoubleForKey(const char* pKey, double value);       void    setStringForKey(const char* pKey, const std::string & value);    //保存到xml文件调用    void    flush();

下面是一个简单地测试代码,直接放在HelloWorldScene.cpp中init方法中即可

 

CCUserDefault::sharedUserDefault()->setBoolForKey("isMax",false);    CCUserDefault::sharedUserDefault()->setDoubleForKey("HP",2.0);    CCUserDefault::sharedUserDefault()->setFloatForKey("MP",3.0f);    CCUserDefault::sharedUserDefault()->setIntegerForKey("lv",2);    CCUserDefault::sharedUserDefault()->setStringForKey("name","hjs");    bool ismax = CCUserDefault::sharedUserDefault()->getBoolForKey   ("isMax" );    double hp = CCUserDefault::sharedUserDefault()->getDoubleForKey ("HP"    );    float mp = CCUserDefault::sharedUserDefault()->getFloatForKey  ("MP"    );    int lv = CCUserDefault::sharedUserDefault()->getIntegerForKey("lv"    );    std::string name = CCUserDefault::sharedUserDefault()->getStringForKey ("name"  );    if(ismax)        CCLOG("ismax true");    else        CCLOG("ismax false");    CCLOG("hp:%f",hp);    CCLOG("mp:%f",mp);    CCLOG("lv:%d",lv);    CCLOG("name:%s",name.c_str());    int tmp = CCUserDefault::sharedUserDefault()->getIntegerForKey("tmp",10);    CCLOG("tmp:%d",tmp);

imageimage

测试过程中并发现不调用flush()方法也能及时写到xml文件中,但还是要记得调用。