GameStatistics.cpp 12 KB

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