Cocos2d-3.x_保存数据和读取数据

前端之家收集整理的这篇文章主要介绍了Cocos2d-3.x_保存数据和读取数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__

#include "cocos2d.h"

USING_NS_CC;


class HelloWorld : public cocos2d::Layer
{
public:
    static cocos2d::Scene* createScene();

    virtual bool init();

	// 使用Cocos封装好的API进行写入
	void saveDataByCocosAPI();
	// 使用Cocos封装好的API进行读取
	void readDataByCocosAPI();

	// 使用自定义的API进行写入
	void saveDataByCustomAPI();
	// 使用自定义的API进行读取
	void readDataByCustomAPI();

    CREATE_FUNC(HelloWorld);
};

#endif // __HELLOWORLD_SCENE_H__
#include "HelloWorldScene.h"


Scene* HelloWorld::createScene()
{
    auto scene = Scene::create();
    auto layer = HelloWorld::create();
    scene->addChild(layer);

    return scene;
}

bool HelloWorld::init()
{
    if ( !Layer::init() )
    {
        return false;
    }
    
    Size visibleSize = Director::getInstance()->getVisibleSize();
    Vec2 origin = Director::getInstance()->getVisibleOrigin();

	auto sprite = Sprite::create("HelloWorld.png");
	sprite->setPosition(Vec2(visibleSize.width / 2 + origin.x,visibleSize.height / 2 + origin.y));
	this->addChild(sprite,0);

	this->saveDataByCocosAPI();
	this->readDataByCocosAPI();

	this->saveDataByCustomAPI();
	this->readDataByCustomAPI();

    return true;
}

void HelloWorld::saveDataByCocosAPI()
{
	UserDefault::getInstance()->setBoolForKey("bool",false);
	UserDefault::getInstance()->setDoubleForKey("double",1.00f);
	UserDefault::getInstance()->setFloatForKey("float",1.0f);
	UserDefault::getInstance()->setIntegerForKey("integer",100);
	UserDefault::getInstance()->setStringForKey("string","Hello");

	UserDefault::getInstance()->flush();
}

void HelloWorld::readDataByCocosAPI()
{
	bool iBool = UserDefault::getInstance()->getBoolForKey("bool",false);
	double iDouble = UserDefault::getInstance()->getDoubleForKey("double",0.00f);
	float iFloat = UserDefault::getInstance()->getFloatForKey("float",0.0f);
	int iInteger =  UserDefault::getInstance()->getIntegerForKey("integer",0);
	std::string iString = UserDefault::getInstance()->getStringForKey("string","");

	log("iBool:%d,iDouble:%f,iFloat:%f,iInteger:%d,iString:%s",iBool,iDouble,iFloat,iInteger,iString.c_str());
}

void HelloWorld::saveDataByCustomAPI()
{
	log("%s",FileUtils::getInstance()->getWritablePath().c_str());

	auto fileUtils = FileUtils::getInstance();
	FILE *fp = fopen(fileUtils->fullPathFromRelativeFile("data.txt",fileUtils->getWritablePath()).c_str(),"w");
	fprintf(fp,"Hello World\n");
	fclose(fp);
}

void HelloWorld::readDataByCustomAPI()
{
	auto fileUtils = FileUtils::getInstance();
	std::string str = fileUtils->getStringFromFile(fileUtils->fullPathFromRelativeFile("data.txt",fileUtils->getWritablePath()));
	
	log("str:%s",str.c_str());
}

猜你在找的Cocos2d-x相关文章