BattleAI.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. /*
  2. * BattleAI.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 "BattleAI.h"
  12. #include "StackWithBonuses.h"
  13. #include "EnemyInfo.h"
  14. #include "../../lib/spells/CSpellHandler.h"
  15. #define LOGL(text) print(text)
  16. #define LOGFL(text, formattingEl) print(boost::str(boost::format(text) % formattingEl))
  17. CBattleAI::CBattleAI(void)
  18. : side(-1), wasWaitingForRealize(false), wasUnlockingGs(false)
  19. {
  20. }
  21. CBattleAI::~CBattleAI(void)
  22. {
  23. if(cb)
  24. {
  25. //Restore previous state of CB - it may be shared with the main AI (like VCAI)
  26. cb->waitTillRealize = wasWaitingForRealize;
  27. cb->unlockGsWhenWaiting = wasUnlockingGs;
  28. }
  29. }
  30. void CBattleAI::init(std::shared_ptr<CBattleCallback> CB)
  31. {
  32. setCbc(CB);
  33. cb = CB;
  34. playerID = *CB->getPlayerID();; //TODO should be sth in callback
  35. wasWaitingForRealize = cb->waitTillRealize;
  36. wasUnlockingGs = CB->unlockGsWhenWaiting;
  37. CB->waitTillRealize = true;
  38. CB->unlockGsWhenWaiting = false;
  39. }
  40. BattleAction CBattleAI::activeStack( const CStack * stack )
  41. {
  42. LOG_TRACE_PARAMS(logAi, "stack: %s", stack->nodeName()) ;
  43. setCbc(cb); //TODO: make solid sure that AIs always use their callbacks (need to take care of event handlers too)
  44. try
  45. {
  46. if(stack->type->idNumber == CreatureID::CATAPULT)
  47. return useCatapult(stack);
  48. if(stack->hasBonusOfType(Bonus::SIEGE_WEAPON) && stack->hasBonusOfType(Bonus::HEALER))
  49. {
  50. auto healingTargets = cb->battleGetStacks(CBattleInfoEssentials::ONLY_MINE);
  51. std::map<int, const CStack*> woundHpToStack;
  52. for(auto stack : healingTargets)
  53. if(auto woundHp = stack->MaxHealth() - stack->getFirstHPleft())
  54. woundHpToStack[woundHp] = stack;
  55. if(woundHpToStack.empty())
  56. return BattleAction::makeDefend(stack);
  57. else
  58. return BattleAction::makeHeal(stack, woundHpToStack.rbegin()->second); //last element of the woundHpToStack is the most wounded stack
  59. }
  60. attemptCastingSpell();
  61. if(auto ret = getCbc()->battleIsFinished())
  62. {
  63. //spellcast may finish battle
  64. //send special preudo-action
  65. BattleAction cancel;
  66. cancel.actionType = Battle::CANCEL;
  67. return cancel;
  68. }
  69. if(auto action = considerFleeingOrSurrendering())
  70. return *action;
  71. PotentialTargets targets(stack);
  72. if(targets.possibleAttacks.size())
  73. {
  74. auto hlp = targets.bestAction();
  75. if(hlp.attack.shooting)
  76. return BattleAction::makeShotAttack(stack, hlp.enemy);
  77. else
  78. return BattleAction::makeMeleeAttack(stack, hlp.enemy, hlp.tile);
  79. }
  80. else
  81. {
  82. if(stack->waited())
  83. {
  84. //ThreatMap threatsToUs(stack); // These lines may be usefull but they are't used in the code.
  85. auto dists = getCbc()->battleGetDistances(stack);
  86. const EnemyInfo &ei= *range::min_element(targets.unreachableEnemies, std::bind(isCloser, _1, _2, std::ref(dists)));
  87. if(distToNearestNeighbour(ei.s->position, dists) < GameConstants::BFIELD_SIZE)
  88. {
  89. return goTowards(stack, ei.s->position);
  90. }
  91. }
  92. else
  93. {
  94. return BattleAction::makeWait(stack);
  95. }
  96. }
  97. }
  98. catch(std::exception &e)
  99. {
  100. logAi->error("Exception occurred in %s %s",__FUNCTION__, e.what());
  101. }
  102. return BattleAction::makeDefend(stack);
  103. }
  104. BattleAction CBattleAI::goTowards(const CStack * stack, BattleHex destination)
  105. {
  106. assert(destination.isValid());
  107. auto avHexes = cb->battleGetAvailableHexes(stack, false);
  108. auto reachability = cb->getReachability(stack);
  109. if(vstd::contains(avHexes, destination))
  110. return BattleAction::makeMove(stack, destination);
  111. auto destNeighbours = destination.neighbouringTiles();
  112. if(vstd::contains_if(destNeighbours, [&](BattleHex n) { return stack->coversPos(destination); }))
  113. {
  114. logAi->warn("Warning: already standing on neighbouring tile!");
  115. //We shouldn't even be here...
  116. return BattleAction::makeDefend(stack);
  117. }
  118. vstd::erase_if(destNeighbours, [&](BattleHex hex){ return !reachability.accessibility.accessible(hex, stack); });
  119. if(!avHexes.size() || !destNeighbours.size()) //we are blocked or dest is blocked
  120. {
  121. return BattleAction::makeDefend(stack);
  122. }
  123. if(stack->hasBonusOfType(Bonus::FLYING))
  124. {
  125. // Flying stack doesn't go hex by hex, so we can't backtrack using predecessors.
  126. // We just check all available hexes and pick the one closest to the target.
  127. auto distToDestNeighbour = [&](BattleHex hex) -> int
  128. {
  129. auto nearestNeighbourToHex = vstd::minElementByFun(destNeighbours, [&](BattleHex a)
  130. {return BattleHex::getDistance(a, hex);});
  131. return BattleHex::getDistance(*nearestNeighbourToHex, hex);
  132. };
  133. auto nearestAvailableHex = vstd::minElementByFun(avHexes, distToDestNeighbour);
  134. return BattleAction::makeMove(stack, *nearestAvailableHex);
  135. }
  136. else
  137. {
  138. BattleHex bestNeighbor = destination;
  139. if(distToNearestNeighbour(destination, reachability.distances, &bestNeighbor) > GameConstants::BFIELD_SIZE)
  140. {
  141. return BattleAction::makeDefend(stack);
  142. }
  143. BattleHex currentDest = bestNeighbor;
  144. while(1)
  145. {
  146. assert(currentDest.isValid());
  147. if(vstd::contains(avHexes, currentDest))
  148. return BattleAction::makeMove(stack, currentDest);
  149. currentDest = reachability.predecessors[currentDest];
  150. }
  151. }
  152. }
  153. BattleAction CBattleAI::useCatapult(const CStack * stack)
  154. {
  155. throw std::runtime_error("The method or operation is not implemented.");
  156. }
  157. enum SpellTypes
  158. {
  159. OFFENSIVE_SPELL, TIMED_EFFECT, OTHER
  160. };
  161. SpellTypes spellType(const CSpell *spell)
  162. {
  163. if (spell->isOffensiveSpell())
  164. return OFFENSIVE_SPELL;
  165. if (spell->hasEffects())
  166. return TIMED_EFFECT;
  167. return OTHER;
  168. }
  169. void CBattleAI::attemptCastingSpell()
  170. {
  171. auto hero = cb->battleGetMyHero();
  172. if(!hero)
  173. return;
  174. if(cb->battleCanCastSpell(hero, ECastingMode::HERO_CASTING) != ESpellCastProblem::OK)
  175. return;
  176. LOGL("Casting spells sounds like fun. Let's see...");
  177. //Get all spells we can cast
  178. std::vector<const CSpell*> possibleSpells;
  179. vstd::copy_if(VLC->spellh->objects, std::back_inserter(possibleSpells), [this, hero] (const CSpell *s) -> bool
  180. {
  181. return s->canBeCast(getCbc().get(), ECastingMode::HERO_CASTING, hero) == ESpellCastProblem::OK;
  182. });
  183. LOGFL("I can cast %d spells.", possibleSpells.size());
  184. vstd::erase_if(possibleSpells, [](const CSpell *s)
  185. {return spellType(s) == OTHER; });
  186. LOGFL("I know about workings of %d of them.", possibleSpells.size());
  187. //Get possible spell-target pairs
  188. std::vector<PossibleSpellcast> possibleCasts;
  189. for(auto spell : possibleSpells)
  190. {
  191. for(auto hex : getTargetsToConsider(spell, hero))
  192. {
  193. PossibleSpellcast ps = {spell, hex, 0};
  194. possibleCasts.push_back(ps);
  195. }
  196. }
  197. LOGFL("Found %d spell-target combinations.", possibleCasts.size());
  198. if(possibleCasts.empty())
  199. return;
  200. std::map<const CStack*, int> valueOfStack;
  201. for(auto stack : cb->battleGetStacks())
  202. {
  203. PotentialTargets pt(stack);
  204. valueOfStack[stack] = pt.bestActionValue();
  205. }
  206. auto evaluateSpellcast = [&] (const PossibleSpellcast &ps) -> int
  207. {
  208. const int skillLevel = hero->getSpellSchoolLevel(ps.spell);
  209. const int spellPower = hero->getPrimSkillLevel(PrimarySkill::SPELL_POWER);
  210. switch(spellType(ps.spell))
  211. {
  212. case OFFENSIVE_SPELL:
  213. {
  214. int damageDealt = 0, damageReceived = 0;
  215. auto stacksSuffering = ps.spell->getAffectedStacks(cb.get(), ECastingMode::HERO_CASTING, hero, skillLevel, ps.dest);
  216. if(stacksSuffering.empty())
  217. return -1;
  218. for(auto stack : stacksSuffering)
  219. {
  220. const int dmg = ps.spell->calculateDamage(hero, stack, skillLevel, spellPower);
  221. if(stack->owner == playerID)
  222. damageReceived += dmg;
  223. else
  224. damageDealt += dmg;
  225. }
  226. const int damageDiff = damageDealt - damageReceived * 10;
  227. LOGFL("Casting %s on hex %d would deal { %d %d } damage points among %d stacks.",
  228. ps.spell->name % ps.dest % damageDealt % damageReceived % stacksSuffering.size());
  229. //TODO tactic effect too
  230. return damageDiff;
  231. }
  232. case TIMED_EFFECT:
  233. {
  234. auto stacksAffected = ps.spell->getAffectedStacks(cb.get(), ECastingMode::HERO_CASTING, hero, skillLevel, ps.dest);
  235. if(stacksAffected.empty())
  236. return -1;
  237. int totalGain = 0;
  238. for(const CStack * sta : stacksAffected)
  239. {
  240. StackWithBonuses swb;
  241. swb.stack = sta;
  242. //todo: handle effect actualization in HypotheticChangesToBattleState
  243. ps.spell->getEffects(swb.bonusesToAdd, skillLevel, false, hero->getEnchantPower(ps.spell));
  244. ps.spell->getEffects(swb.bonusesToAdd, skillLevel, true, hero->getEnchantPower(ps.spell));
  245. HypotheticChangesToBattleState state;
  246. state.bonusesOfStacks[swb.stack] = &swb;
  247. PotentialTargets pt(swb.stack, state);
  248. auto newValue = pt.bestActionValue();
  249. auto oldValue = valueOfStack[swb.stack];
  250. auto gain = newValue - oldValue;
  251. if(swb.stack->owner != playerID) //enemy
  252. gain = -gain;
  253. LOGFL("Casting %s on %s would improve the stack by %d points (from %d to %d)",
  254. ps.spell->name % sta->nodeName() % (gain) % (oldValue) % (newValue));
  255. totalGain += gain;
  256. }
  257. LOGFL("Total gain of cast %s at hex %d is %d", ps.spell->name % (ps.dest.hex) % (totalGain));
  258. return totalGain;
  259. }
  260. default:
  261. assert(0);
  262. return 0;
  263. }
  264. };
  265. for(PossibleSpellcast & psc : possibleCasts)
  266. psc.value = evaluateSpellcast(psc);
  267. auto pscValue = [] (const PossibleSpellcast &ps) -> int
  268. {
  269. return ps.value;
  270. };
  271. auto castToPerform = *vstd::maxElementByFun(possibleCasts, pscValue);
  272. LOGFL("Best spell is %s. Will cast.", castToPerform.spell->name);
  273. BattleAction spellcast;
  274. spellcast.actionType = Battle::HERO_SPELL;
  275. spellcast.additionalInfo = castToPerform.spell->id;
  276. spellcast.destinationTile = castToPerform.dest;
  277. spellcast.side = side;
  278. spellcast.stackNumber = (!side) ? -1 : -2;
  279. cb->battleMakeAction(&spellcast);
  280. }
  281. std::vector<BattleHex> CBattleAI::getTargetsToConsider(const CSpell * spell, const ISpellCaster * caster) const
  282. {
  283. const CSpell::TargetInfo targetInfo(spell, caster->getSpellSchoolLevel(spell));
  284. std::vector<BattleHex> ret;
  285. if(targetInfo.massive || targetInfo.type == CSpell::NO_TARGET)
  286. {
  287. ret.push_back(BattleHex());
  288. }
  289. else
  290. {
  291. switch(targetInfo.type)
  292. {
  293. case CSpell::CREATURE:
  294. {
  295. for(const CStack * stack : getCbc()->battleAliveStacks())
  296. {
  297. bool immune = ESpellCastProblem::OK != spell->isImmuneByStack(caster, stack);
  298. bool casterStack = stack->owner == caster->getOwner();
  299. if(!immune)
  300. switch (spell->positiveness)
  301. {
  302. case CSpell::POSITIVE:
  303. if(casterStack || targetInfo.smart)
  304. ret.push_back(stack->position);
  305. break;
  306. case CSpell::NEUTRAL:
  307. ret.push_back(stack->position);
  308. break;
  309. case CSpell::NEGATIVE:
  310. if(!casterStack || targetInfo.smart)
  311. ret.push_back(stack->position);
  312. break;
  313. }
  314. }
  315. }
  316. break;
  317. case CSpell::LOCATION:
  318. {
  319. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  320. if(BattleHex(i).isAvailable())
  321. ret.push_back(i);
  322. }
  323. break;
  324. default:
  325. break;
  326. }
  327. }
  328. return ret;
  329. }
  330. int CBattleAI::distToNearestNeighbour(BattleHex hex, const ReachabilityInfo::TDistances &dists, BattleHex *chosenHex)
  331. {
  332. int ret = 1000000;
  333. for(BattleHex n : hex.neighbouringTiles())
  334. {
  335. if(dists[n] >= 0 && dists[n] < ret)
  336. {
  337. ret = dists[n];
  338. if(chosenHex)
  339. *chosenHex = n;
  340. }
  341. }
  342. return ret;
  343. }
  344. void CBattleAI::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool Side)
  345. {
  346. print("battleStart called");
  347. side = Side;
  348. }
  349. bool CBattleAI::isCloser(const EnemyInfo &ei1, const EnemyInfo &ei2, const ReachabilityInfo::TDistances &dists)
  350. {
  351. return distToNearestNeighbour(ei1.s->position, dists) < distToNearestNeighbour(ei2.s->position, dists);
  352. }
  353. void CBattleAI::print(const std::string &text) const
  354. {
  355. logAi->trace("CBattleAI [%p]: %s", this, text);
  356. }
  357. boost::optional<BattleAction> CBattleAI::considerFleeingOrSurrendering()
  358. {
  359. if(cb->battleCanSurrender(playerID))
  360. {
  361. }
  362. if(cb->battleCanFlee())
  363. {
  364. }
  365. return boost::none;
  366. }