BuyArmy.cpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. * BuyArmy.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 "BuyArmy.h"
  12. #include "../../../lib/mapObjects/CGTownInstance.h"
  13. #include "../AIGateway.h"
  14. #include "../Engine/Nullkiller.h"
  15. namespace NKAI
  16. {
  17. using namespace Goals;
  18. bool BuyArmy::operator==(const BuyArmy & other) const
  19. {
  20. return town == other.town && objid == other.objid;
  21. }
  22. std::string BuyArmy::toString() const
  23. {
  24. return "Buy army at " + town->getNameTranslated();
  25. }
  26. void BuyArmy::accept(AIGateway * ai)
  27. {
  28. ui64 valueBought = 0;
  29. //buy the stacks with largest AI value
  30. auto upgradeSuccessfull = ai->makePossibleUpgrades(town);
  31. auto armyToBuy = ai->nullkiller->armyManager->getArmyAvailableToBuy(town->getUpperArmy(), town);
  32. if(armyToBuy.empty())
  33. {
  34. if(upgradeSuccessfull)
  35. return;
  36. throw cannotFulfillGoalException("No creatures to buy.");
  37. }
  38. for(int i = 0; valueBought < value && i < armyToBuy.size(); i++)
  39. {
  40. auto res = cb->getResourceAmount();
  41. auto & ci = armyToBuy[i];
  42. if(objid != -1 && ci.creID != objid)
  43. continue;
  44. vstd::amin(ci.count, res / ci.cre->getFullRecruitCost());
  45. if(ci.count)
  46. {
  47. cb->recruitCreatures(town, town->getUpperArmy(), ci.creID, ci.count, ci.level);
  48. valueBought += ci.count * ci.cre->getAIValue();
  49. }
  50. }
  51. if(!valueBought)
  52. {
  53. throw cannotFulfillGoalException("No creatures to buy.");
  54. }
  55. if(town->visitingHero && !town->garrisonHero)
  56. {
  57. ai->moveHeroToTile(town->visitablePos(), town->visitingHero.get());
  58. }
  59. }
  60. }