BattleAI.cpp 20 KB

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