很简单的步骤
1.读取配置文件
2.根据配置文件显示敌我阵容
然后细化下。
1.配置文件格式用了JSON
既然用了JSON,就需要找一个JSON解析库,然后COCOS2DX3.0自动了个JSON库:rapidjson
不知道是我经验不足还是什么,然后觉得他自带的JSON解析不是我想要的,然后C++又不支持反射,
所以,我就采用了下面这种方式解析JSON。来让他可以像GSON一样解析JSON。
首先是绑定对应的关系,如INT,STRING,CLASS等
首先你定义一个基类,JsonHelper
enum CEnumJsonTypeMap
{
asInt = 1,
asUInt,
asString,
asInt64,
asUInt64,
asClass,
};
void SetProperty(string name, CEnumJsonTypeMap type, void* addr);
vector<string> m_listName;
vector<void*> m_listPropertyAddr;
vector<CEnumJsonTypeMap> m_listType;
-----------------void JsonHelper::SetProperty(string name, CEnumJsonTypeMap type, void* addr)
{
m_listName.push_back(name);
m_listPropertyAddr.push_back(addr);
m_listType.push_back(type);
}
然后假设你有一个属性类 TestJsonParse
在这个类里面你实现一个构造,
构造里面如这样
TestJsonParse::TestJsonParse(){
testJsonParse1=new TestJsonParse1();
SetProperty("MsgID", asInt, &MsgID);
SetProperty("MsgTitle", asString, &MsgTitle);
SetProperty("MsgContent", asString, &MsgContent);
SetProperty("object", asClass, testJsonParse1);
}
绑定对应的关系
然后JsonHelper里面还要加一点东西,就是要根据类型去解析特定的数据
bool JsonHelper::DeSerialize(const char* str){
rapidjson::Document d;
d.Parse<0>(str);
if (d.HasParseError()) //解析错误
{
CCLOG("GetParseError %s\n",d.GetParseError());
}else{
int nSize = m_listName.size();
for (int i=0; i < nSize; ++i ){
void* pAddr = m_listPropertyAddr[i];
switch(m_listType[i]){
case asInt:
(*(int*)pAddr) = d[m_listName[i].c_str()].GetInt();
break;
case asUInt:
(*(unsigned*)pAddr) = d[m_listName[i].c_str()].GetUint();
break;
case asInt64:
(*(int64_t*)pAddr) = d[m_listName[i].c_str()].GetInt64();
break;
case asUInt64:
(*(uint64_t*)pAddr) = d[m_listName[i].c_str()].GetUint64();
break;
case asString:
(*(string*)pAddr) = d[m_listName[i].c_str()].GetString();
break;
case asClass:
const rapidjson::Value &a=d[m_listName[i].c_str()]; //读取中文的数组
JsonHelper* j=static_cast<JsonHelper*>(pAddr);
j->DeSerializeValue(a);
break;
}
}
return true;
}
return false;
}
这样,如果你有这样一个对象的数据{\"MsgContent\":\"哈哈22\",\"MsgID\":1,\"MsgTitle\":\"测试\",\"object\": {\"a\": \"测试\",\"c\": \"测试\",\"e\": \"测试\"}}
就能根据绑定关系一个个解析出来了,然后到时候属性直接调用就好了。