GameStatistics.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. /*
  2. * GameStatistics.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "GameStatistics.h"
  12. #include "../CPlayerState.h"
  13. #include "../constants/StringConstants.h"
  14. #include "../VCMIDirs.h"
  15. #include "CGameState.h"
  16. #include "TerrainHandler.h"
  17. #include "StartInfo.h"
  18. #include "HighScore.h"
  19. #include "../mapObjects/CGHeroInstance.h"
  20. #include "../mapObjects/CGTownInstance.h"
  21. #include "../mapObjects/CGObjectInstance.h"
  22. #include "../mapObjects/MiscObjects.h"
  23. #include "../mapping/CMap.h"
  24. #include "../entities/building/CBuilding.h"
  25. #include "../serializer/JsonDeserializer.h"
  26. #include "../serializer/JsonUpdater.h"
  27. #include "../entities/ResourceTypeHandler.h"
  28. VCMI_LIB_NAMESPACE_BEGIN
  29. void StatisticDataSet::add(StatisticDataSetEntry entry)
  30. {
  31. data.push_back(entry);
  32. }
  33. StatisticDataSetEntry StatisticDataSet::createEntry(const PlayerState * ps, const CGameState * gs, const StatisticDataSet & accumulatedData)
  34. {
  35. StatisticDataSetEntry data;
  36. HighScoreParameter param = HighScore::prepareHighScores(gs, ps->color, false);
  37. HighScoreCalculation scenarioHighScores;
  38. scenarioHighScores.parameters.push_back(param);
  39. scenarioHighScores.isCampaign = false;
  40. data.map = gs->getMap().name.toString();
  41. data.timestamp = std::time(nullptr);
  42. data.day = gs->getDate(Date::DAY);
  43. data.player = ps->color;
  44. data.playerName = gs->getStartInfo()->playerInfos.at(ps->color).name;
  45. data.team = ps->team;
  46. data.isHuman = ps->isHuman();
  47. data.status = ps->status;
  48. data.resources = ps->resources;
  49. data.numberHeroes = ps->getHeroes().size();
  50. data.numberTowns = gs->howManyTowns(ps->color);
  51. data.numberArtifacts = Statistic::getNumberOfArts(ps);
  52. data.numberDwellings = Statistic::getNumberOfDwellings(ps);
  53. data.armyStrength = Statistic::getArmyStrength(ps, true);
  54. data.totalExperience = Statistic::getTotalExperience(ps);
  55. data.income = Statistic::getIncome(gs, ps);
  56. data.mapExploredRatio = Statistic::getMapExploredRatio(gs, ps->color);
  57. data.obeliskVisitedRatio = Statistic::getObeliskVisitedRatio(gs, ps->team);
  58. data.townBuiltRatio = Statistic::getTownBuiltRatio(ps);
  59. data.hasGrail = param.hasGrail;
  60. data.numMines = Statistic::getNumMines(gs, ps);
  61. data.score = scenarioHighScores.calculate().total;
  62. data.maxHeroLevel = Statistic::findBestHero(gs, ps->color) ? Statistic::findBestHero(gs, ps->color)->level : 0;
  63. data.numBattlesNeutral = accumulatedData.accumulatedValues.count(ps->color) ? accumulatedData.accumulatedValues.at(ps->color).numBattlesNeutral : 0;
  64. data.numBattlesPlayer = accumulatedData.accumulatedValues.count(ps->color) ? accumulatedData.accumulatedValues.at(ps->color).numBattlesPlayer : 0;
  65. data.numWinBattlesNeutral = accumulatedData.accumulatedValues.count(ps->color) ? accumulatedData.accumulatedValues.at(ps->color).numWinBattlesNeutral : 0;
  66. data.numWinBattlesPlayer = accumulatedData.accumulatedValues.count(ps->color) ? accumulatedData.accumulatedValues.at(ps->color).numWinBattlesPlayer : 0;
  67. data.numHeroSurrendered = accumulatedData.accumulatedValues.count(ps->color) ? accumulatedData.accumulatedValues.at(ps->color).numHeroSurrendered : 0;
  68. data.numHeroEscaped = accumulatedData.accumulatedValues.count(ps->color) ? accumulatedData.accumulatedValues.at(ps->color).numHeroEscaped : 0;
  69. data.spentResourcesForArmy = accumulatedData.accumulatedValues.count(ps->color) ? accumulatedData.accumulatedValues.at(ps->color).spentResourcesForArmy : TResources();
  70. data.spentResourcesForBuildings = accumulatedData.accumulatedValues.count(ps->color) ? accumulatedData.accumulatedValues.at(ps->color).spentResourcesForBuildings : TResources();
  71. data.tradeVolume = accumulatedData.accumulatedValues.count(ps->color) ? accumulatedData.accumulatedValues.at(ps->color).tradeVolume : TResources();
  72. data.eventCapturedTown = accumulatedData.accumulatedValues.count(ps->color) ? accumulatedData.accumulatedValues.at(ps->color).lastCapturedTownDay == gs->getDate(Date::DAY) : false;
  73. data.eventDefeatedStrongestHero = accumulatedData.accumulatedValues.count(ps->color) ? accumulatedData.accumulatedValues.at(ps->color).lastDefeatedStrongestHeroDay == gs->getDate(Date::DAY) : false;
  74. data.movementPointsUsed = accumulatedData.accumulatedValues.count(ps->color) ? accumulatedData.accumulatedValues.at(ps->color).movementPointsUsed : 0;
  75. return data;
  76. }
  77. void StatisticDataSetEntry::serializeJson(JsonSerializeFormat & handler)
  78. {
  79. handler.serializeString("map", map);
  80. handler.serializeInt("timestamp", timestamp);
  81. handler.serializeInt("day", day);
  82. handler.serializeId("player", player, PlayerColor::CANNOT_DETERMINE);
  83. handler.serializeString("playerName", playerName);
  84. handler.serializeInt("team", team);
  85. handler.serializeBool("isHuman", isHuman);
  86. handler.serializeEnum("status", status, {"ingame", "loser", "winner"});
  87. resources.serializeJson(handler, "resources");
  88. handler.serializeInt("numberHeroes", numberHeroes);
  89. handler.serializeInt("numberTowns", numberTowns);
  90. handler.serializeInt("numberArtifacts", numberArtifacts);
  91. handler.serializeInt("numberDwellings", numberDwellings);
  92. handler.serializeInt("armyStrength", armyStrength);
  93. handler.serializeInt("totalExperience", totalExperience);
  94. handler.serializeInt("income", income);
  95. handler.serializeFloat("mapExploredRatio", mapExploredRatio);
  96. handler.serializeFloat("obeliskVisitedRatio", obeliskVisitedRatio);
  97. handler.serializeFloat("townBuiltRatio", townBuiltRatio);
  98. handler.serializeBool("hasGrail", hasGrail);
  99. {
  100. auto zonesData = handler.enterStruct("numMines");
  101. for(auto & idx : LIBRARY->resourceTypeHandler->getAllObjects())
  102. handler.serializeInt(idx.toResource()->getJsonKey(), numMines[idx], 0);
  103. }
  104. handler.serializeInt("score", score);
  105. handler.serializeInt("maxHeroLevel", maxHeroLevel);
  106. handler.serializeInt("numBattlesNeutral", numBattlesNeutral);
  107. handler.serializeInt("numBattlesPlayer", numBattlesPlayer);
  108. handler.serializeInt("numWinBattlesNeutral", numWinBattlesNeutral);
  109. handler.serializeInt("numWinBattlesPlayer", numWinBattlesPlayer);
  110. handler.serializeInt("numHeroSurrendered", numHeroSurrendered);
  111. handler.serializeInt("numHeroEscaped", numHeroEscaped);
  112. spentResourcesForArmy.serializeJson(handler, "spentResourcesForArmy");
  113. spentResourcesForBuildings.serializeJson(handler, "spentResourcesForBuildings");
  114. tradeVolume.serializeJson(handler, "tradeVolume");
  115. handler.serializeBool("eventCapturedTown", eventCapturedTown);
  116. handler.serializeBool("eventDefeatedStrongestHero", eventDefeatedStrongestHero);
  117. handler.serializeInt("movementPointsUsed", movementPointsUsed);
  118. }
  119. void StatisticDataSet::PlayerAccumulatedValueStorage::serializeJson(JsonSerializeFormat & handler)
  120. {
  121. handler.serializeInt("numBattlesNeutral", numBattlesNeutral);
  122. handler.serializeInt("numBattlesPlayer", numBattlesPlayer);
  123. handler.serializeInt("numWinBattlesNeutral", numWinBattlesNeutral);
  124. handler.serializeInt("numWinBattlesPlayer", numWinBattlesPlayer);
  125. handler.serializeInt("numHeroSurrendered", numHeroSurrendered);
  126. handler.serializeInt("numHeroEscaped", numHeroEscaped);
  127. spentResourcesForArmy.serializeJson(handler, "spentResourcesForArmy");
  128. spentResourcesForBuildings.serializeJson(handler, "spentResourcesForBuildings");
  129. tradeVolume.serializeJson(handler, "tradeVolume");
  130. handler.serializeInt("movementPointsUsed", movementPointsUsed);
  131. handler.serializeInt("lastCapturedTownDay", lastCapturedTownDay);
  132. handler.serializeInt("lastDefeatedStrongestHeroDay", lastDefeatedStrongestHeroDay);
  133. }
  134. void StatisticDataSet::serializeJson(JsonSerializeFormat & handler)
  135. {
  136. {
  137. auto eventsHandler = handler.enterArray("data");
  138. eventsHandler.syncSize(data, JsonNode::JsonType::DATA_VECTOR);
  139. eventsHandler.serializeStruct(data);
  140. }
  141. {
  142. auto eventsHandler = handler.enterStruct("accumulatedValues");
  143. for(auto & val : accumulatedValues)
  144. eventsHandler->serializeStruct(GameConstants::PLAYER_COLOR_NAMES[val.first], val.second);
  145. }
  146. }
  147. std::string StatisticDataSet::toCsv(std::string sep) const
  148. {
  149. std::stringstream ss;
  150. auto resources = LIBRARY->resourceTypeHandler->getAllObjects();
  151. ss << "Map" << sep;
  152. ss << "Timestamp" << sep;
  153. ss << "Day" << sep;
  154. ss << "Player" << sep;
  155. ss << "PlayerName" << sep;
  156. ss << "Team" << sep;
  157. ss << "IsHuman" << sep;
  158. ss << "Status" << sep;
  159. ss << "NumberHeroes" << sep;
  160. ss << "NumberTowns" << sep;
  161. ss << "NumberArtifacts" << sep;
  162. ss << "NumberDwellings" << sep;
  163. ss << "ArmyStrength" << sep;
  164. ss << "TotalExperience" << sep;
  165. ss << "Income" << sep;
  166. ss << "MapExploredRatio" << sep;
  167. ss << "ObeliskVisitedRatio" << sep;
  168. ss << "TownBuiltRatio" << sep;
  169. ss << "HasGrail" << sep;
  170. ss << "Score" << sep;
  171. ss << "MaxHeroLevel" << sep;
  172. ss << "NumBattlesNeutral" << sep;
  173. ss << "NumBattlesPlayer" << sep;
  174. ss << "NumWinBattlesNeutral" << sep;
  175. ss << "NumWinBattlesPlayer" << sep;
  176. ss << "NumHeroSurrendered" << sep;
  177. ss << "NumHeroEscaped" << sep;
  178. ss << "EventCapturedTown" << sep;
  179. ss << "EventDefeatedStrongestHero" << sep;
  180. ss << "MovementPointsUsed";
  181. for(auto & resource : resources)
  182. ss << sep << resource.toResource()->getJsonKey();
  183. for(auto & resource : resources)
  184. ss << sep << resource.toResource()->getJsonKey() + "Mines";
  185. for(auto & resource : resources)
  186. ss << sep << resource.toResource()->getJsonKey() + "SpentResourcesForArmy";
  187. for(auto & resource : resources)
  188. ss << sep << resource.toResource()->getJsonKey() + "SpentResourcesForBuildings";
  189. for(auto & resource : resources)
  190. ss << sep << resource.toResource()->getJsonKey() + "TradeVolume";
  191. ss << "\r\n";
  192. for(auto & entry : data)
  193. {
  194. ss << entry.map << sep;
  195. ss << vstd::getFormattedDateTime(entry.timestamp, "%Y-%m-%dT%H:%M:%S") << sep;
  196. ss << entry.day << sep;
  197. ss << GameConstants::PLAYER_COLOR_NAMES[entry.player] << sep;
  198. ss << entry.playerName << sep;
  199. ss << entry.team.getNum() << sep;
  200. ss << entry.isHuman << sep;
  201. ss << static_cast<int>(entry.status) << sep;
  202. ss << entry.numberHeroes << sep;
  203. ss << entry.numberTowns << sep;
  204. ss << entry.numberArtifacts << sep;
  205. ss << entry.numberDwellings << sep;
  206. ss << entry.armyStrength << sep;
  207. ss << entry.totalExperience << sep;
  208. ss << entry.income << sep;
  209. ss << entry.mapExploredRatio << sep;
  210. ss << entry.obeliskVisitedRatio << sep;
  211. ss << entry.townBuiltRatio << sep;
  212. ss << entry.hasGrail << sep;
  213. ss << entry.score << sep;
  214. ss << entry.maxHeroLevel << sep;
  215. ss << entry.numBattlesNeutral << sep;
  216. ss << entry.numBattlesPlayer << sep;
  217. ss << entry.numWinBattlesNeutral << sep;
  218. ss << entry.numWinBattlesPlayer << sep;
  219. ss << entry.numHeroSurrendered << sep;
  220. ss << entry.numHeroEscaped << sep;
  221. ss << entry.eventCapturedTown << sep;
  222. ss << entry.eventDefeatedStrongestHero << sep;
  223. ss << entry.movementPointsUsed;
  224. for(auto & resource : resources)
  225. ss << sep << entry.resources[resource];
  226. for(auto & resource : resources)
  227. ss << sep << entry.numMines.at(resource);
  228. for(auto & resource : resources)
  229. ss << sep << entry.spentResourcesForArmy[resource];
  230. for(auto & resource : resources)
  231. ss << sep << entry.spentResourcesForBuildings[resource];
  232. for(auto & resource : resources)
  233. ss << sep << entry.tradeVolume[resource];
  234. ss << "\r\n";
  235. }
  236. return ss.str();
  237. }
  238. std::string StatisticDataSet::writeCsv() const
  239. {
  240. const boost::filesystem::path outPath = VCMIDirs::get().userCachePath() / "statistic";
  241. boost::filesystem::create_directories(outPath);
  242. const boost::filesystem::path filePath = outPath / (vstd::getDateTimeISO8601Basic(std::time(nullptr)) + ".csv");
  243. std::ofstream file(filePath.c_str());
  244. std::string csv = toCsv(";");
  245. file << csv;
  246. return filePath.string();
  247. }
  248. //calculates total number of artifacts that belong to given player
  249. int Statistic::getNumberOfArts(const PlayerState * ps)
  250. {
  251. int ret = 0;
  252. for(auto h : ps->getHeroes())
  253. {
  254. ret += h->artifactsInBackpack.size() + h->artifactsWorn.size();
  255. }
  256. return ret;
  257. }
  258. int Statistic::getNumberOfDwellings(const PlayerState * ps)
  259. {
  260. int ret = 0;
  261. for(const auto * obj : ps->getOwnedObjects())
  262. if (!obj->asOwnable()->providedCreatures().empty())
  263. ret += 1;
  264. return ret;
  265. }
  266. // get total strength of player army
  267. si64 Statistic::getArmyStrength(const PlayerState * ps, bool withTownGarrison)
  268. {
  269. si64 str = 0;
  270. for(auto h : ps->getHeroes())
  271. {
  272. if(!h->isGarrisoned() || withTownGarrison) //original h3 behavior
  273. str += h->getArmyStrength();
  274. }
  275. return str;
  276. }
  277. // get total experience of all heroes
  278. si64 Statistic::getTotalExperience(const PlayerState * ps)
  279. {
  280. si64 tmp = 0;
  281. for(auto h : ps->getHeroes())
  282. tmp += h->exp;
  283. return tmp;
  284. }
  285. // get total gold income
  286. int Statistic::getIncome(const CGameState * gs, const PlayerState * ps)
  287. {
  288. int totalIncome = 0;
  289. //Heroes can produce gold as well - skill, specialty or arts
  290. for(const auto & object : ps->getOwnedObjects())
  291. totalIncome += object->asOwnable()->dailyIncome()[EGameResID::GOLD];
  292. return totalIncome;
  293. }
  294. float Statistic::getMapExploredRatio(const CGameState * gs, PlayerColor player)
  295. {
  296. float visible = 0.0;
  297. float numTiles = 0.0;
  298. for(int layer = 0; layer < gs->getMap().levels(); layer++)
  299. for(int y = 0; y < gs->getMap().height; ++y)
  300. for(int x = 0; x < gs->getMap().width; ++x)
  301. {
  302. TerrainTile tile = gs->getMap().getTile(int3(x, y, layer));
  303. if(tile.blocked() && !tile.visitable())
  304. continue;
  305. if(gs->isVisibleFor(int3(x, y, layer), player))
  306. visible++;
  307. numTiles++;
  308. }
  309. return visible / numTiles;
  310. }
  311. const CGHeroInstance * Statistic::findBestHero(const CGameState * gs, const PlayerColor & color)
  312. {
  313. const auto &h = gs->players.at(color).getHeroes();
  314. if(h.empty())
  315. return nullptr;
  316. //best hero will be that with highest exp
  317. int best = 0;
  318. for(int b=1; b<h.size(); ++b)
  319. {
  320. if(h[b]->exp > h[best]->exp)
  321. {
  322. best = b;
  323. }
  324. }
  325. return h[best];
  326. }
  327. std::vector<std::vector<PlayerColor>> Statistic::getRank(std::vector<std::pair<PlayerColor, si64>> stats)
  328. {
  329. std::sort(stats.begin(), stats.end(), [](const std::pair<PlayerColor, si64> & a, const std::pair<PlayerColor, si64> & b) { return a.second > b.second; });
  330. //put first element
  331. std::vector< std::vector<PlayerColor> > ret;
  332. ret.push_back( { stats[0].first } );
  333. //the rest of elements
  334. for(int g=1; g<stats.size(); ++g)
  335. {
  336. if(stats[g].second == stats[g-1].second)
  337. {
  338. (ret.end()-1)->push_back( stats[g].first );
  339. }
  340. else
  341. {
  342. //create next occupied rank
  343. ret.push_back( { stats[g].first });
  344. }
  345. }
  346. return ret;
  347. }
  348. int Statistic::getObeliskVisited(const CGameState * gs, const TeamID & t)
  349. {
  350. if(gs->getMap().obelisksVisited.count(t))
  351. return gs->getMap().obelisksVisited.at(t);
  352. else
  353. return 0;
  354. }
  355. float Statistic::getObeliskVisitedRatio(const CGameState * gs, const TeamID & t)
  356. {
  357. if(!gs->getMap().obeliskCount)
  358. return 0;
  359. return static_cast<float>(getObeliskVisited(gs, t)) / gs->getMap().obeliskCount;
  360. }
  361. std::map<EGameResID, int> Statistic::getNumMines(const CGameState * gs, const PlayerState * ps)
  362. {
  363. std::map<EGameResID, int> tmp;
  364. for(auto & res : LIBRARY->resourceTypeHandler->getAllObjects())
  365. tmp[res] = 0;
  366. for(const auto * object : ps->getOwnedObjects())
  367. {
  368. //Mines
  369. if(object->ID == Obj::MINE || object->ID == Obj::ABANDONED_MINE)
  370. {
  371. const auto * mine = dynamic_cast<const CGMine *>(object);
  372. assert(mine);
  373. tmp[mine->producedResource]++;
  374. }
  375. }
  376. return tmp;
  377. }
  378. float Statistic::getTownBuiltRatio(const PlayerState * ps)
  379. {
  380. float built = 0.0;
  381. float total = 0.0;
  382. for(const auto & t : ps->getTowns())
  383. {
  384. built += t->getBuildings().size();
  385. for(const auto & b : t->getTown()->buildings)
  386. if(!t->forbiddenBuildings.count(b.first))
  387. total += 1;
  388. }
  389. if(total < 1)
  390. return 0;
  391. return built / total;
  392. }
  393. VCMI_LIB_NAMESPACE_END