BattleAI.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  1. #include "StdInc.h"
  2. #include "../../lib/AI_Base.h"
  3. #include "BattleAI.h"
  4. #include "../../lib/BattleState.h"
  5. #include "../../CCallback.h"
  6. #include "../../lib/CCreatureHandler.h"
  7. #include "../../lib/spells/CSpellHandler.h"
  8. #include "../../lib/VCMI_Lib.h"
  9. using boost::optional;
  10. static std::shared_ptr<CBattleCallback> cbc;
  11. #define LOGL(text) print(text)
  12. #define LOGFL(text, formattingEl) print(boost::str(boost::format(text) % formattingEl))
  13. struct Priorities
  14. {
  15. double manaValue;
  16. double generalResourceValueModifier;
  17. std::vector<double> resourceTypeBaseValues;
  18. std::function<double(const CStack *)> stackEvaluator;
  19. Priorities()
  20. {
  21. manaValue = 0.;
  22. generalResourceValueModifier = 1.;
  23. range::copy(VLC->objh->resVals, std::back_inserter(resourceTypeBaseValues));
  24. stackEvaluator = [](const CStack*){ return 1.0; };
  25. }
  26. };
  27. Priorities *priorities = nullptr;
  28. namespace {
  29. int distToNearestNeighbour(BattleHex hex, const ReachabilityInfo::TDistances& dists, BattleHex *chosenHex = nullptr)
  30. {
  31. int ret = 1000000;
  32. for(BattleHex n : hex.neighbouringTiles())
  33. {
  34. if(dists[n] >= 0 && dists[n] < ret)
  35. {
  36. ret = dists[n];
  37. if(chosenHex)
  38. *chosenHex = n;
  39. }
  40. }
  41. return ret;
  42. }
  43. bool isCloser(const EnemyInfo & ei1, const EnemyInfo & ei2, const ReachabilityInfo::TDistances & dists)
  44. {
  45. return distToNearestNeighbour(ei1.s->position, dists) < distToNearestNeighbour(ei2.s->position, dists);
  46. }
  47. }
  48. template <typename Container, typename Pred>
  49. auto sum(const Container & c, Pred p) -> decltype(p(*std::begin(c)))
  50. {
  51. double ret = 0;
  52. for(const auto &element : c)
  53. {
  54. ret += p(element);
  55. }
  56. return ret;
  57. }
  58. CBattleAI::CBattleAI(void)
  59. : side(-1)
  60. {
  61. print("created");
  62. }
  63. CBattleAI::~CBattleAI(void)
  64. {
  65. print("destroyed");
  66. if(cb)
  67. {
  68. //Restore previous state of CB - it may be shared with the main AI (like VCAI)
  69. cb->waitTillRealize = wasWaitingForRealize;
  70. cb->unlockGsWhenWaiting = wasUnlockingGs;
  71. }
  72. }
  73. void CBattleAI::init(std::shared_ptr<CBattleCallback> CB)
  74. {
  75. print("init called, saving ptr to IBattleCallback");
  76. cbc = cb = CB;
  77. playerID = *CB->getPlayerID();; //TODO should be sth in callback
  78. wasWaitingForRealize = cb->waitTillRealize;
  79. wasUnlockingGs = CB->unlockGsWhenWaiting;
  80. CB->waitTillRealize = true;
  81. CB->unlockGsWhenWaiting = false;
  82. }
  83. static bool thereRemainsEnemy()
  84. {
  85. return !cbc->battleIsFinished();
  86. }
  87. BattleAction CBattleAI::activeStack( const CStack * stack )
  88. {
  89. LOG_TRACE_PARAMS(logAi, "stack: %s", stack->nodeName()) ;
  90. cbc = cb; //TODO: make solid sure that AIs always use their callbacks (need to take care of event handlers too)
  91. try
  92. {
  93. print("activeStack called for " + stack->nodeName());
  94. if(stack->type->idNumber == CreatureID::CATAPULT)
  95. return useCatapult(stack);
  96. if(stack->hasBonusOfType(Bonus::SIEGE_WEAPON) && stack->hasBonusOfType(Bonus::HEALER))
  97. {
  98. auto healingTargets = cb->battleGetStacks(CBattleInfoEssentials::ONLY_MINE);
  99. std::map<int, const CStack*> woundHpToStack;
  100. for(auto stack : healingTargets)
  101. if(auto woundHp = stack->MaxHealth() - stack->firstHPleft)
  102. woundHpToStack[woundHp] = stack;
  103. if(woundHpToStack.empty())
  104. return BattleAction::makeDefend(stack);
  105. else
  106. return BattleAction::makeHeal(stack, woundHpToStack.rbegin()->second); //last element of the woundHpToStack is the most wounded stack
  107. }
  108. if(cb->battleCanCastSpell())
  109. attemptCastingSpell();
  110. if(!thereRemainsEnemy())
  111. return BattleAction();
  112. if(auto action = considerFleeingOrSurrendering())
  113. return *action;
  114. if(cb->battleGetStacks(CBattleInfoEssentials::ONLY_ENEMY).empty())
  115. {
  116. //We apparently won battle by casting spell, return defend... (accessing cb may cause trouble)
  117. return BattleAction::makeDefend(stack);
  118. }
  119. PotentialTargets targets(stack);
  120. if(targets.possibleAttacks.size())
  121. {
  122. auto hlp = targets.bestAction();
  123. if(hlp.attack.shooting)
  124. return BattleAction::makeShotAttack(stack, hlp.enemy);
  125. else
  126. return BattleAction::makeMeleeAttack(stack, hlp.enemy, hlp.tile);
  127. }
  128. else
  129. {
  130. if(stack->waited())
  131. {
  132. ThreatMap threatsToUs(stack);
  133. auto dists = cbc->battleGetDistances(stack);
  134. const EnemyInfo &ei= *range::min_element(targets.unreachableEnemies, std::bind(isCloser, _1, _2, std::ref(dists)));
  135. if(distToNearestNeighbour(ei.s->position, dists) < GameConstants::BFIELD_SIZE)
  136. {
  137. return goTowards(stack, ei.s->position);
  138. }
  139. }
  140. else
  141. {
  142. return BattleAction::makeWait(stack);
  143. }
  144. }
  145. }
  146. catch(std::exception &e)
  147. {
  148. logAi->errorStream() << "Exception occurred in " << __FUNCTION__ << " " << e.what();
  149. }
  150. return BattleAction::makeDefend(stack);
  151. }
  152. void CBattleAI::actionFinished(const BattleAction &action)
  153. {
  154. print("actionFinished called");
  155. }
  156. void CBattleAI::actionStarted(const BattleAction &action)
  157. {
  158. print("actionStarted called");
  159. }
  160. void CBattleAI::battleAttack(const BattleAttack *ba)
  161. {
  162. print("battleAttack called");
  163. }
  164. void CBattleAI::battleStacksAttacked(const std::vector<BattleStackAttacked> & bsa)
  165. {
  166. print("battleStacksAttacked called");
  167. }
  168. void CBattleAI::battleEnd(const BattleResult *br)
  169. {
  170. print("battleEnd called");
  171. }
  172. void CBattleAI::battleNewRoundFirst(int round)
  173. {
  174. print("battleNewRoundFirst called");
  175. }
  176. void CBattleAI::battleNewRound(int round)
  177. {
  178. print("battleNewRound called");
  179. }
  180. void CBattleAI::battleStackMoved(const CStack * stack, std::vector<BattleHex> dest, int distance)
  181. {
  182. print("battleStackMoved called");;
  183. }
  184. void CBattleAI::battleSpellCast(const BattleSpellCast *sc)
  185. {
  186. print("battleSpellCast called");
  187. }
  188. void CBattleAI::battleStacksEffectsSet(const SetStackEffect & sse)
  189. {
  190. print("battleStacksEffectsSet called");
  191. }
  192. void CBattleAI::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool Side)
  193. {
  194. print("battleStart called");
  195. side = Side;
  196. }
  197. void CBattleAI::battleStacksHealedRes(const std::vector<std::pair<ui32, ui32> > & healedStacks, bool lifeDrain, bool tentHeal, si32 lifeDrainFrom)
  198. {
  199. print("battleStacksHealedRes called");
  200. }
  201. void CBattleAI::battleNewStackAppeared(const CStack * stack)
  202. {
  203. print("battleNewStackAppeared called");
  204. }
  205. void CBattleAI::battleObstaclesRemoved(const std::set<si32> & removedObstacles)
  206. {
  207. print("battleObstaclesRemoved called");
  208. }
  209. void CBattleAI::battleCatapultAttacked(const CatapultAttack & ca)
  210. {
  211. print("battleCatapultAttacked called");
  212. }
  213. void CBattleAI::battleStacksRemoved(const BattleStacksRemoved & bsr)
  214. {
  215. print("battleStacksRemoved called");
  216. }
  217. void CBattleAI::print(const std::string &text) const
  218. {
  219. logAi->traceStream() << "CBattleAI [" << this <<"]: " << text;
  220. }
  221. BattleAction CBattleAI::goTowards(const CStack * stack, BattleHex destination)
  222. {
  223. assert(destination.isValid());
  224. auto avHexes = cb->battleGetAvailableHexes(stack, false);
  225. auto reachability = cb->getReachability(stack);
  226. if(vstd::contains(avHexes, destination))
  227. return BattleAction::makeMove(stack, destination);
  228. auto destNeighbours = destination.neighbouringTiles();
  229. if(vstd::contains_if(destNeighbours, [&](BattleHex n) { return stack->coversPos(destination); }))
  230. {
  231. logAi->warnStream() << "Warning: already standing on neighbouring tile!";
  232. //We shouldn't even be here...
  233. return BattleAction::makeDefend(stack);
  234. }
  235. vstd::erase_if(destNeighbours, [&](BattleHex hex){ return !reachability.accessibility.accessible(hex, stack); });
  236. if(!avHexes.size() || !destNeighbours.size()) //we are blocked or dest is blocked
  237. {
  238. print("goTowards: Stack cannot move! That's " + stack->nodeName());
  239. return BattleAction::makeDefend(stack);
  240. }
  241. if(stack->hasBonusOfType(Bonus::FLYING))
  242. {
  243. // Flying stack doesn't go hex by hex, so we can't backtrack using predecessors.
  244. // We just check all available hexes and pick the one closest to the target.
  245. auto distToDestNeighbour = [&](BattleHex hex) -> int
  246. {
  247. auto nearestNeighbourToHex = vstd::minElementByFun(destNeighbours, [&](BattleHex a)
  248. {
  249. return BattleHex::getDistance(a, hex);
  250. });
  251. return BattleHex::getDistance(*nearestNeighbourToHex, hex);
  252. };
  253. auto nearestAvailableHex = vstd::minElementByFun(avHexes, distToDestNeighbour);
  254. return BattleAction::makeMove(stack, *nearestAvailableHex);
  255. }
  256. else
  257. {
  258. BattleHex bestNeighbor = destination;
  259. if(distToNearestNeighbour(destination, reachability.distances, &bestNeighbor) > GameConstants::BFIELD_SIZE)
  260. {
  261. print("goTowards: Cannot reach");
  262. return BattleAction::makeDefend(stack);
  263. }
  264. BattleHex currentDest = bestNeighbor;
  265. while(1)
  266. {
  267. assert(currentDest.isValid());
  268. if(vstd::contains(avHexes, currentDest))
  269. return BattleAction::makeMove(stack, currentDest);
  270. currentDest = reachability.predecessors[currentDest];
  271. }
  272. }
  273. }
  274. BattleAction CBattleAI::useCatapult(const CStack * stack)
  275. {
  276. throw std::runtime_error("The method or operation is not implemented.");
  277. }
  278. enum SpellTypes
  279. {
  280. OFFENSIVE_SPELL, TIMED_EFFECT, OTHER
  281. };
  282. SpellTypes spellType(const CSpell *spell)
  283. {
  284. if (spell->isOffensiveSpell())
  285. return OFFENSIVE_SPELL;
  286. if (spell->hasEffects())
  287. return TIMED_EFFECT;
  288. return OTHER;
  289. }
  290. struct PossibleSpellcast
  291. {
  292. const CSpell *spell;
  293. BattleHex dest;
  294. };
  295. struct CurrentOffensivePotential
  296. {
  297. std::map<const CStack *, PotentialTargets> ourAttacks;
  298. std::map<const CStack *, PotentialTargets> enemyAttacks;
  299. CurrentOffensivePotential(ui8 side)
  300. {
  301. for(auto stack : cbc->battleGetStacks())
  302. {
  303. if(stack->attackerOwned == !side)
  304. ourAttacks[stack] = PotentialTargets(stack);
  305. else
  306. enemyAttacks[stack] = PotentialTargets(stack);
  307. }
  308. }
  309. int potentialValue()
  310. {
  311. int ourPotential = 0, enemyPotential = 0;
  312. for(auto &p : ourAttacks)
  313. ourPotential += p.second.bestAction().attackValue();
  314. for(auto &p : enemyAttacks)
  315. enemyPotential += p.second.bestAction().attackValue();
  316. return ourPotential - enemyPotential;
  317. }
  318. };
  319. //
  320. // //set has its own order, so remove_if won't work. TODO - reuse for map
  321. // template<typename Elem, typename Predicate>
  322. // void erase_if(std::set<Elem> &setContainer, Predicate pred)
  323. // {
  324. // auto itr = setContainer.begin();
  325. // auto endItr = setContainer.end();
  326. // while(itr != endItr)
  327. // {
  328. // auto tmpItr = itr++;
  329. // if(pred(*tmpItr))
  330. // setContainer.erase(tmpItr);
  331. // }
  332. // }
  333. void CBattleAI::attemptCastingSpell()
  334. {
  335. LOGL("Casting spells sounds like fun. Let's see...");
  336. auto hero = cb->battleGetMyHero();
  337. //auto known = cb->battleGetFightingHero(side);
  338. //Get all spells we can cast
  339. std::vector<const CSpell*> possibleSpells;
  340. vstd::copy_if(VLC->spellh->objects, std::back_inserter(possibleSpells), [this] (const CSpell *s) -> bool
  341. {
  342. auto problem = cbc->battleCanCastThisSpell(s);
  343. return problem == ESpellCastProblem::OK;
  344. });
  345. LOGFL("I can cast %d spells.", possibleSpells.size());
  346. vstd::erase_if(possibleSpells, [](const CSpell *s)
  347. {return spellType(s) == OTHER; });
  348. LOGFL("I know about workings of %d of them.", possibleSpells.size());
  349. //Get possible spell-target pairs
  350. std::vector<PossibleSpellcast> possibleCasts;
  351. for(auto spell : possibleSpells)
  352. {
  353. for(auto hex : getTargetsToConsider(spell))
  354. {
  355. PossibleSpellcast ps = {spell, hex};
  356. possibleCasts.push_back(ps);
  357. }
  358. }
  359. LOGFL("Found %d spell-target combinations.", possibleCasts.size());
  360. if(possibleCasts.empty())
  361. return;
  362. std::map<const CStack*, int> valueOfStack;
  363. for(auto stack : cb->battleGetStacks())
  364. {
  365. PotentialTargets pt(stack);
  366. valueOfStack[stack] = pt.bestActionValue();
  367. }
  368. auto evaluateSpellcast = [&] (const PossibleSpellcast &ps) -> int
  369. {
  370. const int skillLevel = hero->getSpellSchoolLevel(ps.spell);
  371. const int spellPower = hero->getPrimSkillLevel(PrimarySkill::SPELL_POWER);
  372. switch(spellType(ps.spell))
  373. {
  374. case OFFENSIVE_SPELL:
  375. {
  376. int damageDealt = 0, damageReceived = 0;
  377. auto stacksSuffering = ps.spell->getAffectedStacks(cb.get(), ECastingMode::HERO_CASTING, playerID, skillLevel, ps.dest, hero);
  378. if(stacksSuffering.empty())
  379. return -1;
  380. for(auto stack : stacksSuffering)
  381. {
  382. const int dmg = ps.spell->calculateDamage(hero, stack, skillLevel, spellPower);
  383. if(stack->owner == playerID)
  384. damageReceived += dmg;
  385. else
  386. damageDealt += dmg;
  387. }
  388. const int damageDiff = damageDealt - damageReceived;
  389. LOGFL("Casting %s on hex %d would deal %d damage points among %d stacks.",
  390. ps.spell->name % ps.dest % damageDiff % stacksSuffering.size());
  391. //TODO tactic effect too
  392. return damageDiff;
  393. }
  394. case TIMED_EFFECT:
  395. {
  396. StackWithBonuses swb;
  397. swb.stack = cb->battleGetStackByPos(ps.dest);
  398. if(!swb.stack)
  399. return -1;
  400. Bonus pseudoBonus;
  401. pseudoBonus.sid = ps.spell->id;
  402. pseudoBonus.val = skillLevel;
  403. pseudoBonus.turnsRemain = 1; //TODO
  404. CStack::stackEffectToFeature(swb.bonusesToAdd, pseudoBonus);
  405. HypotheticChangesToBattleState state;
  406. state.bonusesOfStacks[swb.stack] = &swb;
  407. PotentialTargets pt(swb.stack, state);
  408. auto newValue = pt.bestActionValue();
  409. auto oldValue = valueOfStack[swb.stack];
  410. auto gain = newValue - oldValue;
  411. if(swb.stack->owner != playerID) //enemy
  412. gain = -gain;
  413. LOGFL("Casting %s on %s would improve the stack by %d points (from %d to %d)",
  414. ps.spell->name % swb.stack->nodeName() % gain % (oldValue) % (newValue));
  415. return gain;
  416. }
  417. default:
  418. assert(0);
  419. return 0;
  420. }
  421. };
  422. auto castToPerform = *vstd::maxElementByFun(possibleCasts, evaluateSpellcast);
  423. LOGFL("Best spell is %s. Will cast.", castToPerform.spell->name);
  424. BattleAction spellcast;
  425. spellcast.actionType = Battle::HERO_SPELL;
  426. spellcast.additionalInfo = castToPerform.spell->id;
  427. spellcast.destinationTile = castToPerform.dest;
  428. spellcast.side = side;
  429. spellcast.stackNumber = (!side) ? -1 : -2;
  430. cb->battleMakeAction(&spellcast);
  431. }
  432. std::vector<BattleHex> CBattleAI::getTargetsToConsider( const CSpell *spell ) const
  433. {
  434. if(spell->getTargetType() == CSpell::NO_TARGET)
  435. {
  436. //Spell can be cast anywhere, all hexes are potentially considerable.
  437. std::vector<BattleHex> ret;
  438. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  439. if(BattleHex(i).isAvailable())
  440. ret.push_back(i);
  441. return ret;
  442. }
  443. else
  444. {
  445. //TODO when massive effect -> doesn't matter where cast
  446. return cbc->battleGetPossibleTargets(playerID, spell);
  447. }
  448. }
  449. boost::optional<BattleAction> CBattleAI::considerFleeingOrSurrendering()
  450. {
  451. if(cb->battleCanSurrender(playerID))
  452. {
  453. }
  454. if(cb->battleCanFlee())
  455. {
  456. }
  457. return boost::none;
  458. }
  459. ThreatMap::ThreatMap(const CStack *Endangered) : endangered(Endangered)
  460. {
  461. sufferedDamage.fill(0);
  462. for(const CStack *enemy : cbc->battleGetStacks())
  463. {
  464. //Consider only stacks of different owner
  465. if(enemy->attackerOwned == endangered->attackerOwned)
  466. continue;
  467. //Look-up which tiles can be melee-attacked
  468. std::array<bool, GameConstants::BFIELD_SIZE> meleeAttackable;
  469. meleeAttackable.fill(false);
  470. auto enemyReachability = cbc->getReachability(enemy);
  471. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  472. {
  473. if(enemyReachability.isReachable(i))
  474. {
  475. meleeAttackable[i] = true;
  476. for(auto n : BattleHex(i).neighbouringTiles())
  477. meleeAttackable[n] = true;
  478. }
  479. }
  480. //Gather possible assaults
  481. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  482. {
  483. if(cbc->battleCanShoot(enemy, i))
  484. threatMap[i].push_back(BattleAttackInfo(enemy, endangered, true));
  485. else if(meleeAttackable[i])
  486. {
  487. BattleAttackInfo bai(enemy, endangered, false);
  488. bai.chargedFields = std::max(BattleHex::getDistance(enemy->position, i) - 1, 0); //TODO check real distance (BFS), not just metric
  489. threatMap[i].push_back(BattleAttackInfo(bai));
  490. }
  491. }
  492. }
  493. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  494. {
  495. sufferedDamage[i] = sum(threatMap[i], [](const BattleAttackInfo &bai) -> int
  496. {
  497. auto dmg = cbc->calculateDmgRange(bai);
  498. return (dmg.first + dmg.second)/2;
  499. });
  500. }
  501. }
  502. const TBonusListPtr StackWithBonuses::getAllBonuses(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root /*= nullptr*/, const std::string &cachingStr /*= ""*/) const
  503. {
  504. TBonusListPtr ret = std::make_shared<BonusList>();
  505. const TBonusListPtr originalList = stack->getAllBonuses(selector, limit, root, cachingStr);
  506. range::copy(*originalList, std::back_inserter(*ret));
  507. for(auto &bonus : bonusesToAdd)
  508. {
  509. if(selector(&bonus) && (!limit || !limit(&bonus)))
  510. ret->push_back(&bonus);
  511. }
  512. //TODO limiters?
  513. return ret;
  514. }
  515. int AttackPossibility::damageDiff() const
  516. {
  517. if (!priorities)
  518. priorities = new Priorities;
  519. const auto dealtDmgValue = priorities->stackEvaluator(enemy) * damageDealt;
  520. const auto receivedDmgValue = priorities->stackEvaluator(attack.attacker) * damageReceived;
  521. return dealtDmgValue - receivedDmgValue;
  522. }
  523. int AttackPossibility::attackValue() const
  524. {
  525. return damageDiff() + tacticImpact;
  526. }
  527. AttackPossibility AttackPossibility::evaluate(const BattleAttackInfo &AttackInfo, const HypotheticChangesToBattleState &state, BattleHex hex)
  528. {
  529. auto attacker = AttackInfo.attacker;
  530. auto enemy = AttackInfo.defender;
  531. const int remainingCounterAttacks = getValOr(state.counterAttacksLeft, enemy, enemy->counterAttacksRemaining());
  532. const bool counterAttacksBlocked = attacker->hasBonusOfType(Bonus::BLOCKS_RETALIATION) || enemy->hasBonusOfType(Bonus::NO_RETALIATION);
  533. const int totalAttacks = 1 + AttackInfo.attackerBonuses->getBonuses(Selector::type(Bonus::ADDITIONAL_ATTACK), (Selector::effectRange (Bonus::NO_LIMIT).Or(Selector::effectRange(Bonus::ONLY_MELEE_FIGHT))))->totalValue();
  534. AttackPossibility ap = {enemy, hex, AttackInfo, 0, 0, 0};
  535. auto curBai = AttackInfo; //we'll modify here the stack counts
  536. for(int i = 0; i < totalAttacks; i++)
  537. {
  538. std::pair<ui32, ui32> retaliation(0,0);
  539. auto attackDmg = cbc->battleEstimateDamage(curBai, &retaliation);
  540. ap.damageDealt = (attackDmg.first + attackDmg.second) / 2;
  541. ap.damageReceived = (retaliation.first + retaliation.second) / 2;
  542. if(remainingCounterAttacks <= i || counterAttacksBlocked)
  543. ap.damageReceived = 0;
  544. curBai.attackerCount = attacker->count - attacker->countKilledByAttack(ap.damageReceived).first;
  545. curBai.defenderCount = enemy->count - enemy->countKilledByAttack(ap.damageDealt).first;
  546. if(!curBai.attackerCount)
  547. break;
  548. //TODO what about defender? should we break? but in pessimistic scenario defender might be alive
  549. }
  550. //TODO other damage related to attack (eg. fire shield and other abilities)
  551. //Limit damages by total stack health
  552. vstd::amin(ap.damageDealt, enemy->count * enemy->MaxHealth() - (enemy->MaxHealth() - enemy->firstHPleft));
  553. vstd::amin(ap.damageReceived, attacker->count * attacker->MaxHealth() - (attacker->MaxHealth() - attacker->firstHPleft));
  554. return ap;
  555. }
  556. PotentialTargets::PotentialTargets(const CStack *attacker, const HypotheticChangesToBattleState &state /*= HypotheticChangesToBattleState()*/)
  557. {
  558. auto dists = cbc->battleGetDistances(attacker);
  559. auto avHexes = cbc->battleGetAvailableHexes(attacker, false);
  560. for(const CStack *enemy : cbc->battleGetStacks())
  561. {
  562. //Consider only stacks of different owner
  563. if(enemy->attackerOwned == attacker->attackerOwned)
  564. continue;
  565. auto GenerateAttackInfo = [&](bool shooting, BattleHex hex) -> AttackPossibility
  566. {
  567. auto bai = BattleAttackInfo(attacker, enemy, shooting);
  568. bai.attackerBonuses = getValOr(state.bonusesOfStacks, bai.attacker, bai.attacker);
  569. bai.defenderBonuses = getValOr(state.bonusesOfStacks, bai.defender, bai.defender);
  570. if(hex.isValid())
  571. {
  572. assert(dists[hex] <= attacker->Speed());
  573. bai.chargedFields = dists[hex];
  574. }
  575. return AttackPossibility::evaluate(bai, state, hex);
  576. };
  577. if(cbc->battleCanShoot(attacker, enemy->position))
  578. {
  579. possibleAttacks.push_back(GenerateAttackInfo(true, BattleHex::INVALID));
  580. }
  581. else
  582. {
  583. for(BattleHex hex : avHexes)
  584. if(CStack::isMeleeAttackPossible(attacker, enemy, hex))
  585. possibleAttacks.push_back(GenerateAttackInfo(false, hex));
  586. if(!vstd::contains_if(possibleAttacks, [=](const AttackPossibility &pa) { return pa.enemy == enemy; }))
  587. unreachableEnemies.push_back(enemy);
  588. }
  589. }
  590. }
  591. AttackPossibility PotentialTargets::bestAction() const
  592. {
  593. if(possibleAttacks.empty())
  594. throw std::runtime_error("No best action, since we don't have any actions");
  595. return *vstd::maxElementByFun(possibleAttacks, [](const AttackPossibility &ap) { return ap.attackValue(); } );
  596. }
  597. int PotentialTargets::bestActionValue() const
  598. {
  599. if(possibleAttacks.empty())
  600. return 0;
  601. return bestAction().attackValue();
  602. }
  603. void EnemyInfo::calcDmg(const CStack * ourStack)
  604. {
  605. TDmgRange retal, dmg = cbc->battleEstimateDamage(ourStack, s, &retal);
  606. adi = (dmg.first + dmg.second) / 2;
  607. adr = (retal.first + retal.second) / 2;
  608. }