HeroManager.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. /*
  2. * HeroManager.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 "../Engine/Nullkiller.h"
  12. #include "../../../lib/mapObjects/MapObjects.h"
  13. #include "../../../lib/CHeroHandler.h"
  14. #include "../../../lib/GameSettings.h"
  15. namespace NKAI
  16. {
  17. const SecondarySkillEvaluator HeroManager::wariorSkillsScores = SecondarySkillEvaluator(
  18. {
  19. std::make_shared<SecondarySkillScoreMap>(
  20. std::map<SecondarySkill, float>
  21. {
  22. {SecondarySkill::DIPLOMACY, 2},
  23. {SecondarySkill::LOGISTICS, 2},
  24. {SecondarySkill::EARTH_MAGIC, 2},
  25. {SecondarySkill::ARMORER, 2},
  26. {SecondarySkill::OFFENCE, 2},
  27. {SecondarySkill::AIR_MAGIC, 1},
  28. {SecondarySkill::WISDOM, 1},
  29. {SecondarySkill::LEADERSHIP, 1},
  30. {SecondarySkill::INTELLIGENCE, 1},
  31. {SecondarySkill::RESISTANCE, 1},
  32. {SecondarySkill::MYSTICISM, -1},
  33. {SecondarySkill::SORCERY, -1},
  34. {SecondarySkill::ESTATES, -1},
  35. {SecondarySkill::FIRST_AID, -1},
  36. {SecondarySkill::LEARNING, -1},
  37. {SecondarySkill::SCHOLAR, -1},
  38. {SecondarySkill::EAGLE_EYE, -1},
  39. {SecondarySkill::NAVIGATION, -1}
  40. }),
  41. std::make_shared<ExistingSkillRule>(),
  42. std::make_shared<WisdomRule>(),
  43. std::make_shared<AtLeastOneMagicRule>()
  44. });
  45. const SecondarySkillEvaluator HeroManager::scountSkillsScores = SecondarySkillEvaluator(
  46. {
  47. std::make_shared<SecondarySkillScoreMap>(
  48. std::map<SecondarySkill, float>
  49. {
  50. {SecondarySkill::LOGISTICS, 2},
  51. {SecondarySkill::ESTATES, 2},
  52. {SecondarySkill::PATHFINDING, 1},
  53. {SecondarySkill::SCHOLAR, 1}
  54. }),
  55. std::make_shared<ExistingSkillRule>()
  56. });
  57. float HeroManager::evaluateSecSkill(SecondarySkill skill, const CGHeroInstance * hero) const
  58. {
  59. auto role = getHeroRole(hero);
  60. if(role == HeroRole::MAIN)
  61. return wariorSkillsScores.evaluateSecSkill(hero, skill);
  62. return scountSkillsScores.evaluateSecSkill(hero, skill);
  63. }
  64. float HeroManager::evaluateSpeciality(const CGHeroInstance * hero) const
  65. {
  66. auto heroSpecial = Selector::source(BonusSource::HERO_SPECIAL, BonusSourceID(hero->type->getId()));
  67. auto secondarySkillBonus = Selector::targetSourceType()(BonusSource::SECONDARY_SKILL);
  68. auto specialSecondarySkillBonuses = hero->getBonuses(heroSpecial.And(secondarySkillBonus));
  69. auto secondarySkillBonuses = hero->getBonuses(Selector::sourceTypeSel(BonusSource::SECONDARY_SKILL));
  70. float specialityScore = 0.0f;
  71. for(auto bonus : *secondarySkillBonuses)
  72. {
  73. auto hasBonus = !!specialSecondarySkillBonuses->getFirst(Selector::typeSubtype(bonus->type, bonus->subtype));
  74. if(hasBonus)
  75. {
  76. SecondarySkill bonusSkill = bonus->sid.as<SecondarySkill>();
  77. float bonusScore = wariorSkillsScores.evaluateSecSkill(hero, bonusSkill);
  78. if(bonusScore > 0)
  79. specialityScore += bonusScore * bonusScore * bonusScore;
  80. }
  81. }
  82. return specialityScore;
  83. }
  84. float HeroManager::evaluateFightingStrength(const CGHeroInstance * hero) const
  85. {
  86. return evaluateSpeciality(hero) + wariorSkillsScores.evaluateSecSkills(hero) + hero->level * 1.5f;
  87. }
  88. void HeroManager::update()
  89. {
  90. logAi->trace("Start analysing our heroes");
  91. std::map<const CGHeroInstance *, float> scores;
  92. auto myHeroes = cb->getHeroesInfo();
  93. for(auto & hero : myHeroes)
  94. {
  95. scores[hero] = evaluateFightingStrength(hero);
  96. knownFightingStrength[hero->id] = hero->getFightingStrength();
  97. }
  98. auto scoreSort = [&](const CGHeroInstance * h1, const CGHeroInstance * h2) -> bool
  99. {
  100. return scores.at(h1) > scores.at(h2);
  101. };
  102. int globalMainCount = std::min(((int)myHeroes.size() + 2) / 3, cb->getMapSize().x / 50 + 1);
  103. //vstd::amin(globalMainCount, 1 + (cb->getTownsInfo().size() / 3));
  104. if(cb->getTownsInfo().size() < 4 && globalMainCount > 2)
  105. {
  106. globalMainCount = 2;
  107. }
  108. std::sort(myHeroes.begin(), myHeroes.end(), scoreSort);
  109. heroRoles.clear();
  110. for(auto hero : myHeroes)
  111. {
  112. heroRoles[hero] = (globalMainCount--) > 0 ? HeroRole::MAIN : HeroRole::SCOUT;
  113. }
  114. for(auto hero : myHeroes)
  115. {
  116. logAi->trace("Hero %s has role %s", hero->getNameTranslated(), heroRoles[hero] == HeroRole::MAIN ? "main" : "scout");
  117. }
  118. }
  119. HeroRole HeroManager::getHeroRole(const HeroPtr & hero) const
  120. {
  121. return heroRoles.at(hero);
  122. }
  123. const std::map<HeroPtr, HeroRole> & HeroManager::getHeroRoles() const
  124. {
  125. return heroRoles;
  126. }
  127. int HeroManager::selectBestSkill(const HeroPtr & hero, const std::vector<SecondarySkill> & skills) const
  128. {
  129. auto role = getHeroRole(hero);
  130. auto & evaluator = role == HeroRole::MAIN ? wariorSkillsScores : scountSkillsScores;
  131. int result = 0;
  132. float resultScore = -100;
  133. for(int i = 0; i < skills.size(); i++)
  134. {
  135. auto score = evaluator.evaluateSecSkill(hero.get(), skills[i]);
  136. if(score > resultScore)
  137. {
  138. resultScore = score;
  139. result = i;
  140. }
  141. logAi->trace(
  142. "Hero %s is proposed to learn %d with score %f",
  143. hero.name,
  144. skills[i].toEnum(),
  145. score);
  146. }
  147. return result;
  148. }
  149. float HeroManager::evaluateHero(const CGHeroInstance * hero) const
  150. {
  151. return evaluateFightingStrength(hero);
  152. }
  153. bool HeroManager::heroCapReached() const
  154. {
  155. const bool includeGarnisoned = true;
  156. int heroCount = cb->getHeroCount(ai->playerID, includeGarnisoned);
  157. return heroCount >= ALLOWED_ROAMING_HEROES
  158. || heroCount >= ai->settings->getMaxRoamingHeroes()
  159. || heroCount >= VLC->settings()->getInteger(EGameSettings::HEROES_PER_PLAYER_ON_MAP_CAP)
  160. || heroCount >= VLC->settings()->getInteger(EGameSettings::HEROES_PER_PLAYER_TOTAL_CAP);
  161. }
  162. float HeroManager::getFightingStrengthCached(const CGHeroInstance * hero) const
  163. {
  164. auto cached = knownFightingStrength.find(hero->id);
  165. return cached != knownFightingStrength.end() ? cached->second : hero->getFightingStrength();
  166. }
  167. float HeroManager::getMagicStrength(const CGHeroInstance * hero) const
  168. {
  169. auto hasFly = hero->spellbookContainsSpell(SpellID::FLY);
  170. auto hasTownPortal = hero->spellbookContainsSpell(SpellID::TOWN_PORTAL);
  171. auto manaLimit = hero->manaLimit();
  172. auto spellPower = hero->getPrimSkillLevel(PrimarySkill::SPELL_POWER);
  173. auto hasEarth = hero->getSpellSchoolLevel(SpellID(SpellID::TOWN_PORTAL).toSpell()) > 0;
  174. auto score = 0.0f;
  175. for(auto spellId : hero->getSpellsInSpellbook())
  176. {
  177. auto spell = spellId.toSpell();
  178. auto schoolLevel = hero->getSpellSchoolLevel(spell);
  179. score += (spell->getLevel() + 1) * (schoolLevel + 1) * 0.05f;
  180. }
  181. vstd::amin(score, 1);
  182. score *= std::min(1.0f, spellPower / 10.0f);
  183. if(hasFly)
  184. score += 0.3f;
  185. if(hasTownPortal && hasEarth)
  186. score += 0.6f;
  187. vstd::amin(score, 1);
  188. score *= std::min(1.0f, manaLimit / 100.0f);
  189. return std::min(score, 1.0f);
  190. }
  191. bool HeroManager::canRecruitHero(const CGTownInstance * town) const
  192. {
  193. if(!town)
  194. town = findTownWithTavern();
  195. if(!town || !townHasFreeTavern(town))
  196. return false;
  197. if(cb->getResourceAmount(EGameResID::GOLD) < GameConstants::HERO_GOLD_COST)
  198. return false;
  199. if(heroCapReached())
  200. return false;
  201. if(!cb->getAvailableHeroes(town).size())
  202. return false;
  203. return true;
  204. }
  205. const CGTownInstance * HeroManager::findTownWithTavern() const
  206. {
  207. for(const CGTownInstance * t : cb->getTownsInfo())
  208. if(townHasFreeTavern(t))
  209. return t;
  210. return nullptr;
  211. }
  212. const CGHeroInstance * HeroManager::findHeroWithGrail() const
  213. {
  214. for(const CGHeroInstance * h : cb->getHeroesInfo())
  215. {
  216. if(h->hasArt(ArtifactID::GRAIL))
  217. return h;
  218. }
  219. return nullptr;
  220. }
  221. const CGHeroInstance * HeroManager::findWeakHeroToDismiss(uint64_t armyLimit) const
  222. {
  223. const CGHeroInstance * weakestHero = nullptr;
  224. auto myHeroes = ai->cb->getHeroesInfo();
  225. for(auto existingHero : myHeroes)
  226. {
  227. if(ai->getHeroLockedReason(existingHero) == HeroLockedReason::DEFENCE
  228. || existingHero->getArmyStrength() >armyLimit
  229. || getHeroRole(existingHero) == HeroRole::MAIN
  230. || existingHero->movementPointsRemaining()
  231. || existingHero->artifactsWorn.size() > (existingHero->hasSpellbook() ? 2 : 1))
  232. {
  233. continue;
  234. }
  235. if(!weakestHero || weakestHero->getFightingStrength() > existingHero->getFightingStrength())
  236. {
  237. weakestHero = existingHero;
  238. }
  239. }
  240. return weakestHero;
  241. }
  242. SecondarySkillScoreMap::SecondarySkillScoreMap(std::map<SecondarySkill, float> scoreMap)
  243. :scoreMap(scoreMap)
  244. {
  245. }
  246. void SecondarySkillScoreMap::evaluateScore(const CGHeroInstance * hero, SecondarySkill skill, float & score) const
  247. {
  248. auto it = scoreMap.find(skill);
  249. if(it != scoreMap.end())
  250. {
  251. score = it->second;
  252. }
  253. }
  254. void ExistingSkillRule::evaluateScore(const CGHeroInstance * hero, SecondarySkill skill, float & score) const
  255. {
  256. int upgradesLeft = 0;
  257. for(auto & heroSkill : hero->secSkills)
  258. {
  259. if(heroSkill.first == skill)
  260. return;
  261. upgradesLeft += MasteryLevel::EXPERT - heroSkill.second;
  262. }
  263. if(score >= 2 || (score >= 1 && upgradesLeft <= 1))
  264. score += 1.5;
  265. }
  266. void WisdomRule::evaluateScore(const CGHeroInstance * hero, SecondarySkill skill, float & score) const
  267. {
  268. if(skill != SecondarySkill::WISDOM)
  269. return;
  270. auto wisdomLevel = hero->getSecSkillLevel(SecondarySkill::WISDOM);
  271. if(hero->level > 10 && wisdomLevel == MasteryLevel::NONE)
  272. score += 1.5;
  273. }
  274. const std::vector<SecondarySkill> AtLeastOneMagicRule::magicSchools = {
  275. SecondarySkill::AIR_MAGIC,
  276. SecondarySkill::EARTH_MAGIC,
  277. SecondarySkill::FIRE_MAGIC,
  278. SecondarySkill::WATER_MAGIC
  279. };
  280. void AtLeastOneMagicRule::evaluateScore(const CGHeroInstance * hero, SecondarySkill skill, float & score) const
  281. {
  282. if(!vstd::contains(magicSchools, skill))
  283. return;
  284. bool heroHasAnyMagic = vstd::contains_if(magicSchools, [&](SecondarySkill skill) -> bool
  285. {
  286. return hero->getSecSkillLevel(skill) > MasteryLevel::NONE;
  287. });
  288. if(!heroHasAnyMagic)
  289. score += 1;
  290. }
  291. SecondarySkillEvaluator::SecondarySkillEvaluator(std::vector<std::shared_ptr<ISecondarySkillRule>> evaluationRules)
  292. : evaluationRules(evaluationRules)
  293. {
  294. }
  295. float SecondarySkillEvaluator::evaluateSecSkills(const CGHeroInstance * hero) const
  296. {
  297. float totalScore = 0;
  298. for(auto skill : hero->secSkills)
  299. {
  300. totalScore += skill.second * evaluateSecSkill(hero, skill.first);
  301. }
  302. return totalScore;
  303. }
  304. float SecondarySkillEvaluator::evaluateSecSkill(const CGHeroInstance * hero, SecondarySkill skill) const
  305. {
  306. float score = 0;
  307. for(auto rule : evaluationRules)
  308. rule->evaluateScore(hero, skill, score);
  309. return score;
  310. }
  311. }