GameStatistics.cpp 12 KB

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