前端之家收集整理的这篇文章主要介绍了
Cocos2d-x_保存数据和读取数据,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
//
// HelloWorldScene.h
//
#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__
#include "cocos2d.h"
#include "cocos-ext.h"
USING_NS_CC;
USING_NS_CC_EXT;
class HelloWorld : public cocos2d::CCLayer
{
public:
virtual bool init();
static cocos2d::CCScene* scene();
CREATE_FUNC(HelloWorld);
void saveGameData();
};
#endif
//
// HelloWorldScene.cpp
//
#include "HelloWorldScene.h"
#include "SimpleAudioEngine.h"
USING_NS_CC;
using namespace std;
using namespace CocosDenshion;
CCScene* HelloWorld::scene()
{
CCScene *scene = CCScene::create();
HelloWorld *layer = HelloWorld::create();
scene->addChild(layer);
return scene;
}
bool HelloWorld::init()
{
if ( !CCLayer::init() )
{
return false;
}
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
CCLabelTTF *pLabelTTF = CCLabelTTF::create("","Helvetica",25);
pLabelTTF->setPosition(ccp(winSize.width*0.5,winSize.height*0.5));
this->addChild(pLabelTTF,90);
this->saveGameData();
return true;
}
void HelloWorld::saveGameData()
{
CCLabelTTF *pttf = (CCLabelTTF *)this->getChildByTag(90);
if (CCUserDefault::sharedUserDefault()->getBoolForKey("bool",false))
{
pttf->setString("有存档,开始读取数据!");
// 读取数据
bool iBool = CCUserDefault::sharedUserDefault()->getBoolForKey("bool",false);
double iDouble = CCUserDefault::sharedUserDefault()->getDoubleForKey("double",0.0);
float iFloat = CCUserDefault::sharedUserDefault()->getFloatForKey("float",0.0);
int iInteger = CCUserDefault::sharedUserDefault()->getIntegerForKey("integer",0);
string iString = CCUserDefault::sharedUserDefault()->getStringForKey("string","");
CCLOG("iBool:%d,iDouble:%f,iFloat:%f,iInteger:%d,iString:%s",iBool,iDouble,iFloat,iInteger,iString.c_str());
}
else
{
pttf->setString("还没有存档,开始存档数据!");
// 准备写入数据
CCUserDefault::sharedUserDefault()->setBoolForKey("bool",true);
CCUserDefault::sharedUserDefault()->setDoubleForKey("double",9.22);
CCUserDefault::sharedUserDefault()->setFloatForKey("float",8.33);
CCUserDefault::sharedUserDefault()->setIntegerForKey("integer",20);
CCUserDefault::sharedUserDefault()->setStringForKey("string","cxm");
// 提交数据
CCUserDefault::sharedUserDefault()->flush();
}
}