levelinputdata.cpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #include "levelinputdata.h"
  2. using namespace ArduinoJson;
  3. #include <fstream>
  4. using std::ifstream;
  5. using std::ofstream;
  6. LevelInputData::LevelInputData() {
  7. _id = -1 ;
  8. _subid = -1 ;
  9. _time = 0 ;
  10. _difficulty = 0 ;//0-normal 1-hard 2-veryhard
  11. }
  12. bool LevelInputData::readFromFile(string filename)
  13. {
  14. _jewels.clear() ;
  15. ifstream ifs( filename.c_str() ) ;
  16. if( ifs.good() == false ) return false ;
  17. DynamicJsonBuffer buffer ;
  18. JsonObject& root = buffer.parse(ifs) ;
  19. _id = root["No"].as<int>() ;
  20. _name =root["Name"].as<char*>() ;
  21. if( _name.length()>8 ) {
  22. _subid = atof( _name.substr(_name.length()-2).c_str() ) ;
  23. }else{
  24. _subid = 0 ;
  25. }
  26. if( root.containsKey("time") ) {
  27. _time = root["time"].as<int>() ;
  28. }else{
  29. _time = root["Duration"].as<int>() ;
  30. }
  31. //如果没有time字段,那么读取Duration字段
  32. _difficulty = root["Difficulty"].as<int>() ;//0-normal 1-hard 2-veryhard
  33. JsonArray& goals = root["Goals"].as<JsonArray>() ;
  34. JsonArray& board = root["Board"].as<JsonArray>() ;
  35. for(int i = 0 ; i<goals.size();++ i ) {
  36. JsonObject& obj1 = goals[i].as<JsonObject>() ;
  37. JewelInputData jid ;
  38. jid._jewelId = obj1["ItemType"].as<int>() ;
  39. jid._count = obj1["Count"].as<int>() ;
  40. _jewels.push_back(jid) ;
  41. }
  42. for(int i = 0 ; i<board.size();++ i ) {
  43. JsonObject& obj1 = board[i].as<JsonObject>() ;
  44. JewelInputData jid ;
  45. jid._jewelId = obj1["ItemType"].as<int>() ;
  46. jid._count = obj1["Count"].as<int>() ;
  47. if( jid._jewelId > 0 ) { //随机宝石暂时不考虑,直接跳过
  48. _jewels.push_back(jid) ;
  49. }
  50. }
  51. return true ;
  52. }
  53. bool LevelInputData::writeToFile(string filename)
  54. {
  55. DynamicJsonBuffer buffer ;
  56. JsonObject& root = buffer.createObject() ;
  57. root["No"] = _id ;
  58. root["Name"] = _name ;
  59. root["time"] = _time ;
  60. root["Duration"] = _time ;
  61. root["Difficulty"] = _difficulty ;
  62. JsonArray& goals = root.createNestedArray("Goals");
  63. JsonArray& board = root.createNestedArray("Board"); //just leave it empty.
  64. for(int i = 0 ; i<_jewels.size();++ i ) {
  65. JsonObject& obj1 = goals.createNestedObject();
  66. obj1["ItemType"] = _jewels[i]._jewelId ;
  67. obj1["Count"] = _jewels[i]._count ;
  68. }
  69. string jsontext ;
  70. root.printTo(jsontext) ;
  71. ofstream ofs( filename.c_str() ) ;
  72. if( ofs.good() == false ) return false ;
  73. ofs<<jsontext ;
  74. ofs.close() ;
  75. return true ;
  76. }