AdventureSpellCast.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. * AdventureSpellCast.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 "AdventureSpellCast.h"
  12. #include "../AIGateway.h"
  13. #include "../../../lib/spells/ISpellMechanics.h"
  14. #include "../../../lib/spells/adventure/TownPortalEffect.h"
  15. namespace NKAI
  16. {
  17. using namespace Goals;
  18. bool AdventureSpellCast::operator==(const AdventureSpellCast & other) const
  19. {
  20. return hero == other.hero;
  21. }
  22. void AdventureSpellCast::accept(AIGateway * ai)
  23. {
  24. if(!hero)
  25. throw cannotFulfillGoalException("Invalid hero!");
  26. auto spell = getSpell();
  27. logAi->trace("Decomposing adventure spell cast of %s for hero %s", spell->getNameTranslated(), hero->getNameTranslated());
  28. if(!spell->isAdventure())
  29. throw cannotFulfillGoalException(spell->getNameTranslated() + " is not an adventure spell.");
  30. if(!hero->canCastThisSpell(spell))
  31. throw cannotFulfillGoalException("Hero can not cast " + spell->getNameTranslated());
  32. if(hero->mana < hero->getSpellCost(spell))
  33. throw cannotFulfillGoalException("Hero has not enough mana to cast " + spell->getNameTranslated());
  34. auto townPortalEffect = spell->getAdventureMechanics().getEffectAs<TownPortalEffect>(hero);
  35. if(town && townPortalEffect)
  36. {
  37. ai->selectedObject = town->id;
  38. if(town->getVisitingHero() && town->tempOwner == ai->playerID && !town->getUpperArmy()->stacksCount())
  39. {
  40. ai->myCb->swapGarrisonHero(town);
  41. }
  42. if(town->getVisitingHero())
  43. throw cannotFulfillGoalException("The town is already occupied by " + town->getVisitingHero()->getNameTranslated());
  44. }
  45. if (hero->isGarrisoned())
  46. ai->myCb->swapGarrisonHero(hero->getVisitedTown());
  47. auto wait = cb->waitTillRealize;
  48. cb->waitTillRealize = true;
  49. cb->castSpell(hero, spellID, tile);
  50. if(town && townPortalEffect)
  51. {
  52. // visit town
  53. ai->moveHeroToTile(town->visitablePos(), hero);
  54. }
  55. cb->waitTillRealize = wait;
  56. throw goalFulfilledException(sptr(*this));
  57. }
  58. std::string AdventureSpellCast::toString() const
  59. {
  60. return "AdventureSpellCast " + spellID.toSpell()->getNameTranslated();
  61. }
  62. }