“家园”的数据的封装

1、封装配置文件的读取:

文件的内容应该是一些静态内容,如游戏的中文内容,飞船的血量初始值等。

先看头文件

#define STATIC_DATA_STRING(key) StaticData::sharedStaticData()->stringFromKey(key)
#define STATIC_DATA_INT(key) StaticData::sharedStaticData()->intFromKey(key)
#define STATIC_DATA_FLOAT(key) StaticData::sharedStaticData()->floatFromKey(key)
#define STATIC_DATA_BOOLEAN(key) StaticData::sharedStaticData()->booleanFromKey(key)
#define STATIC_DATA_POINT(key) StaticData::sharedStaticData()->pointFromKey(key)
#define STATIC_DATA_RECT(key) StaticData::sharedStaticData()->rectFromKey(key)
#define STATIC_DATA_SIZE(key) StaticData::sharedStaticData()->sizeFromKey(key)

class StaticData : public CCObject
{
public:
	static StaticData* sharedStaticData();

	/************************************************************************/
	/* 
		@brief 外部访问接口
		@param key 对应的static_data.plist中的key
		@return 对应的value
	*/
	/************************************************************************/
	const char* stringFromKey(std::string key);
	int intFromKey(std::string key);
	float floatFromKey(std::string key);
	bool booleanFromKey(std::string key);
	CCPoint pointFromKey(std::string key);
	CCRect rectFromKey(std::string key);
	CCSize sizeFromKey(std::string key);

	//内存不足时调用
	void purge();
	/************************************************************************/
	/*  创建get获取器,生成 _staticDstaPath的protected权限的字段,并生成相应get的只读函数  */
	/************************************************************************/
	CC_SYNTHESIZE_READONLY(std::string, _staticDataPath, StaticDataPath);
protected:
	cocos2d::CCDictionary* _dictionary;
private:
	StaticData(void);
	~StaticData(void);
	bool init();
};
从头文件可以看到,这是一个单例,通过shareStaticData()方法访问。并定义了宏进行简单读取。其实现也是很简单(列举部分,其余类推),
bool StaticData::init()
{
	_dictionary = CCDictionary::createWithContentsOfFile(_staticDataPath.c_str());
	//执行retain
	CC_SAFE_RETAIN(_dictionary);
	return true;
}
const char* StaticData::stringFromKey(string key)
{
	return _dictionary->valueForKey(key)->getCString();
}
CCDictionary是一个cocos2d-x引擎自带的一个字典类(即键值对),通过createWithContentsOfFile读取文件(plist文件)后将其值已键值对的方式保存在CCDictionary中。

如在一个配置文件中是这样写的

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>start_game</key>
	<string>开始游戏</string>
</dict>
</plist>
那么就可以通过宏STATIC_DATA_STRING(“start_game”)获取其对应的值了。


2、中文字体的显示:

在win32的开发环境中需要借助iconv库,将从配置文件中读取到的中文转成utf-8格式。

下面的一段代码是从网上找到的一个转换代码

int Config::GBKToUTF8(std::string &gbkStr)      
{      
	iconv_t iconvH;      

	iconvH              = iconv_open("utf-8","gb2312");      
	if(iconvH == 0){      
		return -1;      
	}      
	const char* strChar = gbkStr.c_str();      
	const char** pin    = &strChar;      

	size_t strLength    = gbkStr.length();      
	char* outbuf        = (char*)malloc(strLength*4);      
	char* pBuff         = outbuf;      
	memset(outbuf,0,strLength*4);      
	size_t outLength    = strLength*4;
	#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
	if(-1 == iconv(iconvH,pin,&strLength,&outbuf,&outLength)){
	#elif (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
		if(-1 == iconv(iconvH,(char **)pin,&strLength,&outbuf,&outLength)){
	#endif
		iconv_close(iconvH);      
		return -1;      
	}      
	gbkStr              =   pBuff;      
	iconv_close(iconvH);      
	return 0;      
}
其中,GBKToUTF8是一个静态方法,那么就通过以下方式显示中文
std::string startGame = STATIC_DATA_STRING("start_game");
Config::sharedConfig()->GBKToUTF8(startGame);
CCLabelBMFont* startGameLabel = CCLabelBMFont::create(startGame.c_str(), hw_font_fnt);

3、json文件的读取

在2.2.2版本中,cocos2d-x采用了rapidjson,据说是为了改善性能。那么接下来看下这个读取类的头文件,定义三个文件

class FileUtils {
public:
	//判断文件是否存在
	static bool isFileExist(const char* pFileName);
	//复制文件内容
	static void copyData(const char* pFileName);
	//解析json文件
	static void resolveJsonFile(std::string& fileName, HW_JSON_FILE_TYPE fileType);
};
接下来,主要看resolveJsonFile的主实现,该方法的第一个参数是文件名,第二个时文件类型(不同的文件有不同的内容,需分开处理,故加次参数)

	//定义上下文
	rapidjson::Document doc;
	//获取不同平台的可读写的绝对路径
	std::string jsonFilePath = CCFileUtils::sharedFileUtils()->getWritablePath() + fileName;
	unsigned char* pBuffer = NULL;
	unsigned long bufferSize = 0;
	//读取json文件的内容,存储到pBuffer中
	pBuffer = CCFileUtils::sharedFileUtils()->getFileData(jsonFilePath.c_str(), "r", &bufferSize);
	std::string data((const char*)pBuffer);
	//清掉多余的垃圾字符(如果有的话)
	data = data.substr(0, bufferSize);
	//解析json
	doc.Parse<rapidjson::kParseDefaultFlags>(data.c_str()); 
	//判断json文件是否合法
	if (doc.HasParseError() && !doc.IsArray()) {
		CCLog("get json data false");
		if(pBuffer) {
			delete []pBuffer;
			pBuffer = NULL;
		}
		return;
	}
再接下来应该就是读取内容了,如果要读取的json如下
[
	{
		"id": 1,
		"textureName": "gun_ship.png"
	},
	{
		"id": 2,
		"textureName": "bomb_ship.png"
	}
]
那么只需按以下方式即可读取
		for(unsigned int i=0; i < doc.Size(); i++) {
			rapidjson::Value &v=doc[i];  
			unsigned int id = v["id"].GetInt();
			string textureName = v["textureName"].GetString();
		}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值