GameStatistics.cpp 15 KB

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