BattleAI.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785
  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. BattleAction CBattleAI::activeStack( const CStack * stack )
  84. {
  85. LOG_TRACE_PARAMS(logAi, "stack: %s", stack->nodeName()) ;
  86. cbc = cb; //TODO: make solid sure that AIs always use their callbacks (need to take care of event handlers too)
  87. try
  88. {
  89. print("activeStack called for " + stack->nodeName());
  90. if(stack->type->idNumber == CreatureID::CATAPULT)
  91. return useCatapult(stack);
  92. if(stack->hasBonusOfType(Bonus::SIEGE_WEAPON) && stack->hasBonusOfType(Bonus::HEALER))
  93. {
  94. auto healingTargets = cb->battleGetStacks(CBattleInfoEssentials::ONLY_MINE);
  95. std::map<int, const CStack*> woundHpToStack;
  96. for(auto stack : healingTargets)
  97. if(auto woundHp = stack->MaxHealth() - stack->firstHPleft)
  98. woundHpToStack[woundHp] = stack;
  99. if(woundHpToStack.empty())
  100. return BattleAction::makeDefend(stack);
  101. else
  102. return BattleAction::makeHeal(stack, woundHpToStack.rbegin()->second); //last element of the woundHpToStack is the most wounded stack
  103. }
  104. if(cb->battleCanCastSpell())
  105. attemptCastingSpell();
  106. if(auto ret = cbc->battleIsFinished())
  107. {
  108. //spellcast may finish battle
  109. //send special preudo-action
  110. BattleAction cancel;
  111. cancel.actionType = Battle::CANCEL;
  112. return cancel;
  113. }
  114. if(auto action = considerFleeingOrSurrendering())
  115. return *action;
  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, std::bind(isCloser, _1, _2, std::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->error("Exception occurred in %s %s",__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->trace("CBattleAI [%p]: %s", 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->warn("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->objects, 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, hero))
  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 = ps.spell->getAffectedStacks(cb.get(), ECastingMode::HERO_CASTING, hero, skillLevel, ps.dest);
  375. if(stacksSuffering.empty())
  376. return -1;
  377. for(auto stack : stacksSuffering)
  378. {
  379. const int dmg = ps.spell->calculateDamage(hero, stack, skillLevel, spellPower);
  380. if(stack->owner == playerID)
  381. damageReceived += dmg;
  382. else
  383. damageDealt += dmg;
  384. }
  385. const int damageDiff = damageDealt - damageReceived;
  386. LOGFL("Casting %s on hex %d would deal %d damage points among %d stacks.",
  387. ps.spell->name % ps.dest % damageDiff % stacksSuffering.size());
  388. //TODO tactic effect too
  389. return damageDiff;
  390. }
  391. case TIMED_EFFECT:
  392. {
  393. auto stacksAffected = ps.spell->getAffectedStacks(cb.get(), ECastingMode::HERO_CASTING, hero, skillLevel, ps.dest);
  394. if(stacksAffected.empty())
  395. return -1;
  396. int totalGain = 0;
  397. for(const CStack * sta : stacksAffected)
  398. {
  399. StackWithBonuses swb;
  400. swb.stack = sta;
  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 % sta->nodeName() % (gain) % (oldValue) % (newValue));
  416. totalGain += gain;
  417. }
  418. LOGFL("Total gain of cast %s at hex %d is %d", ps.spell->name % (ps.dest.hex) % (totalGain));
  419. return totalGain;
  420. }
  421. default:
  422. assert(0);
  423. return 0;
  424. }
  425. };
  426. auto castToPerform = *vstd::maxElementByFun(possibleCasts, evaluateSpellcast);
  427. LOGFL("Best spell is %s. Will cast.", castToPerform.spell->name);
  428. BattleAction spellcast;
  429. spellcast.actionType = Battle::HERO_SPELL;
  430. spellcast.additionalInfo = castToPerform.spell->id;
  431. spellcast.destinationTile = castToPerform.dest;
  432. spellcast.side = side;
  433. spellcast.stackNumber = (!side) ? -1 : -2;
  434. cb->battleMakeAction(&spellcast);
  435. }
  436. std::vector<BattleHex> CBattleAI::getTargetsToConsider(const CSpell * spell, const ISpellCaster * caster) const
  437. {
  438. const CSpell::TargetInfo targetInfo(spell, caster->getSpellSchoolLevel(spell));
  439. std::vector<BattleHex> ret;
  440. if(targetInfo.massive || targetInfo.type == CSpell::NO_TARGET)
  441. {
  442. ret.push_back(BattleHex());
  443. }
  444. else
  445. {
  446. switch(targetInfo.type)
  447. {
  448. case CSpell::CREATURE:
  449. {
  450. for(const CStack * stack : cbc->battleAliveStacks())
  451. {
  452. bool immune = ESpellCastProblem::OK != spell->isImmuneByStack(caster, stack);
  453. bool casterStack = stack->owner == caster->getOwner();
  454. if(!immune)
  455. switch (spell->positiveness)
  456. {
  457. case CSpell::POSITIVE:
  458. if(casterStack || targetInfo.smart)
  459. ret.push_back(stack->position);
  460. break;
  461. case CSpell::NEUTRAL:
  462. ret.push_back(stack->position);
  463. break;
  464. case CSpell::NEGATIVE:
  465. if(!casterStack || targetInfo.smart)
  466. ret.push_back(stack->position);
  467. break;
  468. }
  469. }
  470. }
  471. break;
  472. case CSpell::LOCATION:
  473. {
  474. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  475. if(BattleHex(i).isAvailable())
  476. ret.push_back(i);
  477. }
  478. break;
  479. default:
  480. break;
  481. }
  482. }
  483. return ret;
  484. }
  485. boost::optional<BattleAction> CBattleAI::considerFleeingOrSurrendering()
  486. {
  487. if(cb->battleCanSurrender(playerID))
  488. {
  489. }
  490. if(cb->battleCanFlee())
  491. {
  492. }
  493. return boost::none;
  494. }
  495. ThreatMap::ThreatMap(const CStack *Endangered) : endangered(Endangered)
  496. {
  497. sufferedDamage.fill(0);
  498. for(const CStack *enemy : cbc->battleGetStacks())
  499. {
  500. //Consider only stacks of different owner
  501. if(enemy->attackerOwned == endangered->attackerOwned)
  502. continue;
  503. //Look-up which tiles can be melee-attacked
  504. std::array<bool, GameConstants::BFIELD_SIZE> meleeAttackable;
  505. meleeAttackable.fill(false);
  506. auto enemyReachability = cbc->getReachability(enemy);
  507. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  508. {
  509. if(enemyReachability.isReachable(i))
  510. {
  511. meleeAttackable[i] = true;
  512. for(auto n : BattleHex(i).neighbouringTiles())
  513. meleeAttackable[n] = true;
  514. }
  515. }
  516. //Gather possible assaults
  517. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  518. {
  519. if(cbc->battleCanShoot(enemy, i))
  520. threatMap[i].push_back(BattleAttackInfo(enemy, endangered, true));
  521. else if(meleeAttackable[i])
  522. {
  523. BattleAttackInfo bai(enemy, endangered, false);
  524. bai.chargedFields = std::max(BattleHex::getDistance(enemy->position, i) - 1, 0); //TODO check real distance (BFS), not just metric
  525. threatMap[i].push_back(BattleAttackInfo(bai));
  526. }
  527. }
  528. }
  529. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  530. {
  531. sufferedDamage[i] = sum(threatMap[i], [](const BattleAttackInfo &bai) -> int
  532. {
  533. auto dmg = cbc->calculateDmgRange(bai);
  534. return (dmg.first + dmg.second)/2;
  535. });
  536. }
  537. }
  538. const TBonusListPtr StackWithBonuses::getAllBonuses(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root /*= nullptr*/, const std::string &cachingStr /*= ""*/) const
  539. {
  540. TBonusListPtr ret = std::make_shared<BonusList>();
  541. const TBonusListPtr originalList = stack->getAllBonuses(selector, limit, root, cachingStr);
  542. range::copy(*originalList, std::back_inserter(*ret));
  543. for(auto &bonus : bonusesToAdd)
  544. {
  545. if(selector(&bonus) && (!limit || !limit(&bonus)))
  546. ret->push_back(&bonus);
  547. }
  548. //TODO limiters?
  549. return ret;
  550. }
  551. int AttackPossibility::damageDiff() const
  552. {
  553. if (!priorities)
  554. priorities = new Priorities;
  555. const auto dealtDmgValue = priorities->stackEvaluator(enemy) * damageDealt;
  556. const auto receivedDmgValue = priorities->stackEvaluator(attack.attacker) * damageReceived;
  557. return dealtDmgValue - receivedDmgValue;
  558. }
  559. int AttackPossibility::attackValue() const
  560. {
  561. return damageDiff() + tacticImpact;
  562. }
  563. AttackPossibility AttackPossibility::evaluate(const BattleAttackInfo &AttackInfo, const HypotheticChangesToBattleState &state, BattleHex hex)
  564. {
  565. auto attacker = AttackInfo.attacker;
  566. auto enemy = AttackInfo.defender;
  567. const int remainingCounterAttacks = getValOr(state.counterAttacksLeft, enemy, enemy->counterAttacksRemaining());
  568. const bool counterAttacksBlocked = attacker->hasBonusOfType(Bonus::BLOCKS_RETALIATION) || enemy->hasBonusOfType(Bonus::NO_RETALIATION);
  569. 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();
  570. AttackPossibility ap = {enemy, hex, AttackInfo, 0, 0, 0};
  571. auto curBai = AttackInfo; //we'll modify here the stack counts
  572. for(int i = 0; i < totalAttacks; i++)
  573. {
  574. std::pair<ui32, ui32> retaliation(0,0);
  575. auto attackDmg = cbc->battleEstimateDamage(CRandomGenerator::getDefault(), curBai, &retaliation);
  576. ap.damageDealt = (attackDmg.first + attackDmg.second) / 2;
  577. ap.damageReceived = (retaliation.first + retaliation.second) / 2;
  578. if(remainingCounterAttacks <= i || counterAttacksBlocked)
  579. ap.damageReceived = 0;
  580. curBai.attackerCount = attacker->count - attacker->countKilledByAttack(ap.damageReceived).first;
  581. curBai.defenderCount = enemy->count - enemy->countKilledByAttack(ap.damageDealt).first;
  582. if(!curBai.attackerCount)
  583. break;
  584. //TODO what about defender? should we break? but in pessimistic scenario defender might be alive
  585. }
  586. //TODO other damage related to attack (eg. fire shield and other abilities)
  587. //Limit damages by total stack health
  588. vstd::amin(ap.damageDealt, enemy->count * enemy->MaxHealth() - (enemy->MaxHealth() - enemy->firstHPleft));
  589. vstd::amin(ap.damageReceived, attacker->count * attacker->MaxHealth() - (attacker->MaxHealth() - attacker->firstHPleft));
  590. return ap;
  591. }
  592. PotentialTargets::PotentialTargets(const CStack *attacker, const HypotheticChangesToBattleState &state /*= HypotheticChangesToBattleState()*/)
  593. {
  594. auto dists = cbc->battleGetDistances(attacker);
  595. auto avHexes = cbc->battleGetAvailableHexes(attacker, false);
  596. for(const CStack *enemy : cbc->battleGetStacks())
  597. {
  598. //Consider only stacks of different owner
  599. if(enemy->attackerOwned == attacker->attackerOwned)
  600. continue;
  601. auto GenerateAttackInfo = [&](bool shooting, BattleHex hex) -> AttackPossibility
  602. {
  603. auto bai = BattleAttackInfo(attacker, enemy, shooting);
  604. bai.attackerBonuses = getValOr(state.bonusesOfStacks, bai.attacker, bai.attacker);
  605. bai.defenderBonuses = getValOr(state.bonusesOfStacks, bai.defender, bai.defender);
  606. if(hex.isValid())
  607. {
  608. assert(dists[hex] <= attacker->Speed());
  609. bai.chargedFields = dists[hex];
  610. }
  611. return AttackPossibility::evaluate(bai, state, hex);
  612. };
  613. if(cbc->battleCanShoot(attacker, enemy->position))
  614. {
  615. possibleAttacks.push_back(GenerateAttackInfo(true, BattleHex::INVALID));
  616. }
  617. else
  618. {
  619. for(BattleHex hex : avHexes)
  620. if(CStack::isMeleeAttackPossible(attacker, enemy, hex))
  621. possibleAttacks.push_back(GenerateAttackInfo(false, hex));
  622. if(!vstd::contains_if(possibleAttacks, [=](const AttackPossibility &pa) { return pa.enemy == enemy; }))
  623. unreachableEnemies.push_back(enemy);
  624. }
  625. }
  626. }
  627. AttackPossibility PotentialTargets::bestAction() const
  628. {
  629. if(possibleAttacks.empty())
  630. throw std::runtime_error("No best action, since we don't have any actions");
  631. return *vstd::maxElementByFun(possibleAttacks, [](const AttackPossibility &ap) { return ap.attackValue(); } );
  632. }
  633. int PotentialTargets::bestActionValue() const
  634. {
  635. if(possibleAttacks.empty())
  636. return 0;
  637. return bestAction().attackValue();
  638. }
  639. void EnemyInfo::calcDmg(const CStack * ourStack)
  640. {
  641. TDmgRange retal, dmg = cbc->battleEstimateDamage(CRandomGenerator::getDefault(), ourStack, s, &retal);
  642. adi = (dmg.first + dmg.second) / 2;
  643. adr = (retal.first + retal.second) / 2;
  644. }