GameStatistics.cpp 12 KB

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