BattleAI.cpp 21 KB

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