BuyArmyBehavior.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. * BuyArmyBehavior.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 "BuyArmyBehavior.h"
  12. #include "../AIGateway.h"
  13. #include "../AIUtility.h"
  14. #include "../Goals/BuyArmy.h"
  15. #include "../Engine/Nullkiller.h"
  16. namespace NKAI
  17. {
  18. using namespace Goals;
  19. std::string BuyArmyBehavior::toString() const
  20. {
  21. return "Buy army";
  22. }
  23. Goals::TGoalVec BuyArmyBehavior::decompose(const Nullkiller * ai) const
  24. {
  25. Goals::TGoalVec tasks;
  26. auto heroes = cb->getHeroesInfo();
  27. if(heroes.empty())
  28. {
  29. return tasks;
  30. }
  31. ai->dangerHitMap->updateHitMap();
  32. for(auto town : cb->getTownsInfo())
  33. {
  34. //If we can recruit a hero that comes with more army than he costs, we are better off spending our gold on them
  35. if (ai->heroManager->canRecruitHero(town))
  36. {
  37. auto availableHeroes = ai->cb->getAvailableHeroes(town);
  38. for (auto hero : availableHeroes)
  39. {
  40. if (hero->getArmyCost() > GameConstants::HERO_GOLD_COST)
  41. return tasks;
  42. }
  43. }
  44. uint8_t closestThreat = UINT8_MAX;
  45. for (auto threat : ai->dangerHitMap->getTownThreats(town))
  46. {
  47. closestThreat = std::min(closestThreat, threat.turn);
  48. }
  49. if (closestThreat >=2 && ai->buildAnalyzer->isGoldPressureHigh() && !town->hasBuilt(BuildingID::CITY_HALL) && cb->canBuildStructure(town, BuildingID::CITY_HALL) != EBuildingState::FORBIDDEN)
  50. {
  51. return tasks;
  52. }
  53. auto townArmyAvailableToBuy = ai->armyManager->getArmyAvailableToBuyAsCCreatureSet(
  54. town,
  55. ai->getFreeResources());
  56. for(const CGHeroInstance * targetHero : heroes)
  57. {
  58. if(ai->heroManager->getHeroRole(targetHero) == HeroRole::MAIN)
  59. {
  60. auto reinforcement = ai->armyManager->howManyReinforcementsCanGet(
  61. targetHero,
  62. targetHero,
  63. &*townArmyAvailableToBuy);
  64. if(reinforcement)
  65. vstd::amin(reinforcement, ai->armyManager->howManyReinforcementsCanBuy(town->getUpperArmy(), town));
  66. if(reinforcement)
  67. {
  68. tasks.push_back(Goals::sptr(Goals::BuyArmy(town, reinforcement).setpriority(5)));
  69. }
  70. }
  71. }
  72. }
  73. return tasks;
  74. }
  75. }