BuyArmy.cpp 1.6 KB

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