GameStatistics.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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->map->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. std::vector<const CGMine *> Statistic::getMines(const CGameState * gs, const PlayerState * ps)
  176. {
  177. std::vector<const CGMine *> tmp;
  178. std::vector<const CGObjectInstance *> ownedObjects;
  179. for(const CGObjectInstance * obj : gs->map->objects)
  180. {
  181. if(obj && obj->tempOwner == ps->color)
  182. ownedObjects.push_back(obj);
  183. }
  184. /// This is code from CPlayerSpecificInfoCallback::getMyObjects
  185. /// I'm really need to find out about callback interface design...
  186. for(const auto * object : ownedObjects)
  187. {
  188. //Mines
  189. if ( object->ID == Obj::MINE )
  190. {
  191. const auto * mine = dynamic_cast<const CGMine *>(object);
  192. assert(mine);
  193. tmp.push_back(mine);
  194. }
  195. }
  196. return tmp;
  197. }
  198. //calculates total number of artifacts that belong to given player
  199. int Statistic::getNumberOfArts(const PlayerState * ps)
  200. {
  201. int ret = 0;
  202. for(auto h : ps->getHeroes())
  203. {
  204. ret += h->artifactsInBackpack.size() + h->artifactsWorn.size();
  205. }
  206. return ret;
  207. }
  208. int Statistic::getNumberOfDwellings(const PlayerState * ps)
  209. {
  210. int ret = 0;
  211. for(const auto * obj : ps->getOwnedObjects())
  212. if (!obj->asOwnable()->providedCreatures().empty())
  213. ret += 1;
  214. return ret;
  215. }
  216. // get total strength of player army
  217. si64 Statistic::getArmyStrength(const PlayerState * ps, bool withTownGarrison)
  218. {
  219. si64 str = 0;
  220. for(auto h : ps->getHeroes())
  221. {
  222. if(!h->inTownGarrison || withTownGarrison) //original h3 behavior
  223. str += h->getArmyStrength();
  224. }
  225. return str;
  226. }
  227. // get total experience of all heroes
  228. si64 Statistic::getTotalExperience(const PlayerState * ps)
  229. {
  230. si64 tmp = 0;
  231. for(auto h : ps->getHeroes())
  232. tmp += h->exp;
  233. return tmp;
  234. }
  235. // get total gold income
  236. int Statistic::getIncome(const CGameState * gs, const PlayerState * ps)
  237. {
  238. int totalIncome = 0;
  239. //Heroes can produce gold as well - skill, specialty or arts
  240. for(const auto & h : ps->getHeroes())
  241. totalIncome += h->dailyIncome()[EGameResID::GOLD];
  242. //Add town income of all towns
  243. for(const auto & t : ps->getTowns())
  244. totalIncome += t->dailyIncome()[EGameResID::GOLD];
  245. for(const CGMine * mine : getMines(gs, ps))
  246. totalIncome += mine->dailyIncome()[EGameResID::GOLD];
  247. return totalIncome;
  248. }
  249. float Statistic::getMapExploredRatio(const CGameState * gs, PlayerColor player)
  250. {
  251. float visible = 0.0;
  252. float numTiles = 0.0;
  253. for(int layer = 0; layer < (gs->map->twoLevel ? 2 : 1); layer++)
  254. for(int y = 0; y < gs->map->height; ++y)
  255. for(int x = 0; x < gs->map->width; ++x)
  256. {
  257. TerrainTile tile = gs->map->getTile(int3(x, y, layer));
  258. if(tile.blocked() && !tile.visitable())
  259. continue;
  260. if(gs->isVisible(int3(x, y, layer), player))
  261. visible++;
  262. numTiles++;
  263. }
  264. return visible / numTiles;
  265. }
  266. const CGHeroInstance * Statistic::findBestHero(const CGameState * gs, const PlayerColor & color)
  267. {
  268. const auto &h = gs->players.at(color).getHeroes();
  269. if(h.empty())
  270. return nullptr;
  271. //best hero will be that with highest exp
  272. int best = 0;
  273. for(int b=1; b<h.size(); ++b)
  274. {
  275. if(h[b]->exp > h[best]->exp)
  276. {
  277. best = b;
  278. }
  279. }
  280. return h[best];
  281. }
  282. std::vector<std::vector<PlayerColor>> Statistic::getRank(std::vector<std::pair<PlayerColor, si64>> stats)
  283. {
  284. std::sort(stats.begin(), stats.end(), [](const std::pair<PlayerColor, si64> & a, const std::pair<PlayerColor, si64> & b) { return a.second > b.second; });
  285. //put first element
  286. std::vector< std::vector<PlayerColor> > ret;
  287. ret.push_back( { stats[0].first } );
  288. //the rest of elements
  289. for(int g=1; g<stats.size(); ++g)
  290. {
  291. if(stats[g].second == stats[g-1].second)
  292. {
  293. (ret.end()-1)->push_back( stats[g].first );
  294. }
  295. else
  296. {
  297. //create next occupied rank
  298. ret.push_back( { stats[g].first });
  299. }
  300. }
  301. return ret;
  302. }
  303. int Statistic::getObeliskVisited(const CGameState * gs, const TeamID & t)
  304. {
  305. if(gs->map->obelisksVisited.count(t))
  306. return gs->map->obelisksVisited.at(t);
  307. else
  308. return 0;
  309. }
  310. float Statistic::getObeliskVisitedRatio(const CGameState * gs, const TeamID & t)
  311. {
  312. if(!gs->map->obeliskCount)
  313. return 0;
  314. return static_cast<float>(getObeliskVisited(gs, t)) / gs->map->obeliskCount;
  315. }
  316. std::map<EGameResID, int> Statistic::getNumMines(const CGameState * gs, const PlayerState * ps)
  317. {
  318. std::map<EGameResID, int> tmp;
  319. for(auto & res : EGameResID::ALL_RESOURCES())
  320. tmp[res] = 0;
  321. for(const CGMine * mine : getMines(gs, ps))
  322. tmp[mine->producedResource]++;
  323. return tmp;
  324. }
  325. float Statistic::getTownBuiltRatio(const PlayerState * ps)
  326. {
  327. float built = 0.0;
  328. float total = 0.0;
  329. for(const auto & t : ps->getTowns())
  330. {
  331. built += t->getBuildings().size();
  332. for(const auto & b : t->getTown()->buildings)
  333. if(!t->forbiddenBuildings.count(b.first))
  334. total += 1;
  335. }
  336. if(total < 1)
  337. return 0;
  338. return built / total;
  339. }
  340. VCMI_LIB_NAMESPACE_END