一、创建plist文件
在学习《Cocos2d-x 3.x游戏开发之旅》时,点击完屏幕以创建很多炮塔的(x, y)坐标,使用ValueMap把炮塔坐标写入plist文件,保存当前玩家创建的炮塔,以便再次进入游戏时还原之前的炮塔(根据坐标)。下面是创建plist文件的函数:
void TowerPosEditorScene::outputPosToPlistFile()
{
String* s_pFilePath = String::createWithFormat("tollgate/towerPos_level_%d.plist", m_iCurLevel);
outputPosToPlistFile(m_towerPosList, s_pFilePath->getCString());
}
// 输出plist文件————炮台坐标
void TowerPosEditorScene::outputPosToPlistFile(Vector<PosBase*> coll, const char* sFilePath)
{
ValueMap fileDataMap;
int index = 1;// 这里从1开始
for (auto posBase : coll)
{
ValueMap data; // typedef unordered_map<std::string key, Value value> ValueMap;
data["x"] = posBase->getPos().x; // data[key] = value;
data["y"] = posBase->getPos().y; // 注意:fileDataMap为key,data为value
fileDataMap[StringUtils::toString(index)] = Value(data);// fileDataMap[key] = value
index++;
}
// Write a ValueMap into a plist file.
FileUtils::getInstance()->writeToFile(fileDataMap, sFilePath);
}
在outputPosToPlistFile()函数中,首先使用cocos2d::String类创建保存plist文件的”完整路径s_pFilePath变量“,然后把该变量传入重载的outputPosToPlistFile函数。注意
:这里创建文件的方式有点小特别:根据游戏当前等级来命名要创建的plist文件,这样做的好处是,不同等级(或关卡)都会有一份plist文件。
m_towerPosList变量为在在TowerPosEditorScene中声明,用于存储炮塔坐标,PosBase为TowerPos的基类。
二、读取plist文件
玩家创建好炮塔后,点击“输出到文件”后,所有创建的炮塔坐标都存在了plist文件中,那么怎么读取(遍历)plist文件中的炮塔坐标,并把炮塔还原到屏幕呢?作者是这么处理的:
/// 加载坐标对象
Vector<PosBase*> PosLoadUtil::loadPosWithFile(const char* sFilePath, Node* container, int iLevel, bool isDebug)
{
Vector<PosBase*> posList;
ValueMap fileDataMap = FileUtils::getInstance()->getValueMapFromFile(sFilePath);
int size = fileDataMap.size();
for (int i = 1; i <= size; i++)// 注意i从1开始并<=size
{
Value value = fileDataMap[StringUtils::toString(i)];
ValueMap data = value.asValueMap();
PosBase* posBase = TowerPos::create(Point(data["x"].asInt(), data["y"].asInt()), isDebug);
posList.pushBack(posBase);
if (container != NULL)
{
container->addChild(posBase, iLevel);
}
}
return posList;
}
参考:Cocos2d-x 3.x游戏开发之旅 钟迪龙 著