GameStatistics.cpp 12 KB

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