1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- #include "levelinputdata.h"
- using namespace ArduinoJson;
- #include <fstream>
- using std::ifstream;
- using std::ofstream;
- LevelInputData::LevelInputData() {
- _id = -1 ;
- _subid = -1 ;
- _time = 0 ;
- _difficulty = 0 ;//0-normal 1-hard 2-veryhard
- }
- bool LevelInputData::readFromFile(string filename)
- {
- _jewels.clear() ;
- ifstream ifs( filename.c_str() ) ;
- if( ifs.good() == false ) return false ;
- DynamicJsonBuffer buffer ;
- JsonObject& root = buffer.parse(ifs) ;
- _id = root["No"].as<int>() ;
- _name =root["Name"].as<char*>() ;
- if( _name.length()>8 ) {
- _subid = atof( _name.substr(_name.length()-2).c_str() ) ;
- }else{
- _subid = 0 ;
- }
- if( root.containsKey("time") ) {
- _time = root["time"].as<int>() ;
- }else{
- _time = root["Duration"].as<int>() ;
- }
- //如果没有time字段,那么读取Duration字段
- _difficulty = root["Difficulty"].as<int>() ;//0-normal 1-hard 2-veryhard
- JsonArray& goals = root["Goals"].as<JsonArray>() ;
- JsonArray& board = root["Board"].as<JsonArray>() ;
- for(int i = 0 ; i<goals.size();++ i ) {
- JsonObject& obj1 = goals[i].as<JsonObject>() ;
- JewelInputData jid ;
- jid._jewelId = obj1["ItemType"].as<int>() ;
- jid._count = obj1["Count"].as<int>() ;
- _jewels.push_back(jid) ;
- }
- for(int i = 0 ; i<board.size();++ i ) {
- JsonObject& obj1 = board[i].as<JsonObject>() ;
- JewelInputData jid ;
- jid._jewelId = obj1["ItemType"].as<int>() ;
- jid._count = obj1["Count"].as<int>() ;
- if( jid._jewelId > 0 ) { //随机宝石暂时不考虑,直接跳过
- _jewels.push_back(jid) ;
- }
- }
- return true ;
- }
- bool LevelInputData::writeToFile(string filename)
- {
- DynamicJsonBuffer buffer ;
- JsonObject& root = buffer.createObject() ;
- root["No"] = _id ;
- root["Name"] = _name ;
- root["time"] = _time ;
- root["Duration"] = _time ;
- root["Difficulty"] = _difficulty ;
- JsonArray& goals = root.createNestedArray("Goals");
- JsonArray& board = root.createNestedArray("Board"); //just leave it empty.
- for(int i = 0 ; i<_jewels.size();++ i ) {
- JsonObject& obj1 = goals.createNestedObject();
- obj1["ItemType"] = _jewels[i]._jewelId ;
- obj1["Count"] = _jewels[i]._count ;
- }
- string jsontext ;
- root.printTo(jsontext) ;
- ofstream ofs( filename.c_str() ) ;
- if( ofs.good() == false ) return false ;
- ofs<<jsontext ;
- ofs.close() ;
- return true ;
- }
|