BattleAI.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794
  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. si32 value;
  292. };
  293. struct CurrentOffensivePotential
  294. {
  295. std::map<const CStack *, PotentialTargets> ourAttacks;
  296. std::map<const CStack *, PotentialTargets> enemyAttacks;
  297. CurrentOffensivePotential(ui8 side)
  298. {
  299. for(auto stack : cbc->battleGetStacks())
  300. {
  301. if(stack->attackerOwned == !side)
  302. ourAttacks[stack] = PotentialTargets(stack);
  303. else
  304. enemyAttacks[stack] = PotentialTargets(stack);
  305. }
  306. }
  307. int potentialValue()
  308. {
  309. int ourPotential = 0, enemyPotential = 0;
  310. for(auto &p : ourAttacks)
  311. ourPotential += p.second.bestAction().attackValue();
  312. for(auto &p : enemyAttacks)
  313. enemyPotential += p.second.bestAction().attackValue();
  314. return ourPotential - enemyPotential;
  315. }
  316. };
  317. //
  318. // //set has its own order, so remove_if won't work. TODO - reuse for map
  319. // template<typename Elem, typename Predicate>
  320. // void erase_if(std::set<Elem> &setContainer, Predicate pred)
  321. // {
  322. // auto itr = setContainer.begin();
  323. // auto endItr = setContainer.end();
  324. // while(itr != endItr)
  325. // {
  326. // auto tmpItr = itr++;
  327. // if(pred(*tmpItr))
  328. // setContainer.erase(tmpItr);
  329. // }
  330. // }
  331. void CBattleAI::attemptCastingSpell()
  332. {
  333. LOGL("Casting spells sounds like fun. Let's see...");
  334. auto hero = cb->battleGetMyHero();
  335. //auto known = cb->battleGetFightingHero(side);
  336. //Get all spells we can cast
  337. std::vector<const CSpell*> possibleSpells;
  338. vstd::copy_if(VLC->spellh->objects, std::back_inserter(possibleSpells), [this] (const CSpell *s) -> bool
  339. {
  340. auto problem = cbc->battleCanCastThisSpell(s);
  341. return problem == ESpellCastProblem::OK;
  342. });
  343. LOGFL("I can cast %d spells.", possibleSpells.size());
  344. vstd::erase_if(possibleSpells, [](const CSpell *s)
  345. {return spellType(s) == OTHER; });
  346. LOGFL("I know about workings of %d of them.", possibleSpells.size());
  347. //Get possible spell-target pairs
  348. std::vector<PossibleSpellcast> possibleCasts;
  349. for(auto spell : possibleSpells)
  350. {
  351. for(auto hex : getTargetsToConsider(spell, hero))
  352. {
  353. PossibleSpellcast ps = {spell, hex, 0};
  354. possibleCasts.push_back(ps);
  355. }
  356. }
  357. LOGFL("Found %d spell-target combinations.", possibleCasts.size());
  358. if(possibleCasts.empty())
  359. return;
  360. std::map<const CStack*, int> valueOfStack;
  361. for(auto stack : cb->battleGetStacks())
  362. {
  363. PotentialTargets pt(stack);
  364. valueOfStack[stack] = pt.bestActionValue();
  365. }
  366. auto evaluateSpellcast = [&] (const PossibleSpellcast &ps) -> int
  367. {
  368. const int skillLevel = hero->getSpellSchoolLevel(ps.spell);
  369. const int spellPower = hero->getPrimSkillLevel(PrimarySkill::SPELL_POWER);
  370. switch(spellType(ps.spell))
  371. {
  372. case OFFENSIVE_SPELL:
  373. {
  374. int damageDealt = 0, damageReceived = 0;
  375. auto stacksSuffering = ps.spell->getAffectedStacks(cb.get(), ECastingMode::HERO_CASTING, hero, skillLevel, ps.dest);
  376. if(stacksSuffering.empty())
  377. return -1;
  378. for(auto stack : stacksSuffering)
  379. {
  380. const int dmg = ps.spell->calculateDamage(hero, stack, skillLevel, spellPower);
  381. if(stack->owner == playerID)
  382. damageReceived += dmg;
  383. else
  384. damageDealt += dmg;
  385. }
  386. const int damageDiff = damageDealt - damageReceived * 10;
  387. LOGFL("Casting %s on hex %d would deal { %d %d } damage points among %d stacks.",
  388. ps.spell->name % ps.dest % damageDealt % damageReceived % stacksSuffering.size());
  389. //TODO tactic effect too
  390. return damageDiff;
  391. }
  392. case TIMED_EFFECT:
  393. {
  394. auto stacksAffected = ps.spell->getAffectedStacks(cb.get(), ECastingMode::HERO_CASTING, hero, skillLevel, ps.dest);
  395. if(stacksAffected.empty())
  396. return -1;
  397. int totalGain = 0;
  398. for(const CStack * sta : stacksAffected)
  399. {
  400. StackWithBonuses swb;
  401. swb.stack = sta;
  402. Bonus pseudoBonus;
  403. pseudoBonus.sid = ps.spell->id;
  404. pseudoBonus.val = skillLevel;
  405. pseudoBonus.turnsRemain = 1; //TODO
  406. CStack::stackEffectToFeature(swb.bonusesToAdd, pseudoBonus);
  407. HypotheticChangesToBattleState state;
  408. state.bonusesOfStacks[swb.stack] = &swb;
  409. PotentialTargets pt(swb.stack, state);
  410. auto newValue = pt.bestActionValue();
  411. auto oldValue = valueOfStack[swb.stack];
  412. auto gain = newValue - oldValue;
  413. if(swb.stack->owner != playerID) //enemy
  414. gain = -gain;
  415. LOGFL("Casting %s on %s would improve the stack by %d points (from %d to %d)",
  416. ps.spell->name % sta->nodeName() % (gain) % (oldValue) % (newValue));
  417. totalGain += gain;
  418. }
  419. LOGFL("Total gain of cast %s at hex %d is %d", ps.spell->name % (ps.dest.hex) % (totalGain));
  420. return totalGain;
  421. }
  422. default:
  423. assert(0);
  424. return 0;
  425. }
  426. };
  427. for(PossibleSpellcast & psc : possibleCasts)
  428. psc.value = evaluateSpellcast(psc);
  429. auto pscValue = [] (const PossibleSpellcast &ps) -> int
  430. {
  431. return ps.value;
  432. };
  433. auto castToPerform = *vstd::maxElementByFun(possibleCasts, pscValue);
  434. LOGFL("Best spell is %s. Will cast.", castToPerform.spell->name);
  435. BattleAction spellcast;
  436. spellcast.actionType = Battle::HERO_SPELL;
  437. spellcast.additionalInfo = castToPerform.spell->id;
  438. spellcast.destinationTile = castToPerform.dest;
  439. spellcast.side = side;
  440. spellcast.stackNumber = (!side) ? -1 : -2;
  441. cb->battleMakeAction(&spellcast);
  442. }
  443. std::vector<BattleHex> CBattleAI::getTargetsToConsider(const CSpell * spell, const ISpellCaster * caster) const
  444. {
  445. const CSpell::TargetInfo targetInfo(spell, caster->getSpellSchoolLevel(spell));
  446. std::vector<BattleHex> ret;
  447. if(targetInfo.massive || targetInfo.type == CSpell::NO_TARGET)
  448. {
  449. ret.push_back(BattleHex());
  450. }
  451. else
  452. {
  453. switch(targetInfo.type)
  454. {
  455. case CSpell::CREATURE:
  456. {
  457. for(const CStack * stack : cbc->battleAliveStacks())
  458. {
  459. bool immune = ESpellCastProblem::OK != spell->isImmuneByStack(caster, stack);
  460. bool casterStack = stack->owner == caster->getOwner();
  461. if(!immune)
  462. switch (spell->positiveness)
  463. {
  464. case CSpell::POSITIVE:
  465. if(casterStack || targetInfo.smart)
  466. ret.push_back(stack->position);
  467. break;
  468. case CSpell::NEUTRAL:
  469. ret.push_back(stack->position);
  470. break;
  471. case CSpell::NEGATIVE:
  472. if(!casterStack || targetInfo.smart)
  473. ret.push_back(stack->position);
  474. break;
  475. }
  476. }
  477. }
  478. break;
  479. case CSpell::LOCATION:
  480. {
  481. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  482. if(BattleHex(i).isAvailable())
  483. ret.push_back(i);
  484. }
  485. break;
  486. default:
  487. break;
  488. }
  489. }
  490. return ret;
  491. }
  492. boost::optional<BattleAction> CBattleAI::considerFleeingOrSurrendering()
  493. {
  494. if(cb->battleCanSurrender(playerID))
  495. {
  496. }
  497. if(cb->battleCanFlee())
  498. {
  499. }
  500. return boost::none;
  501. }
  502. ThreatMap::ThreatMap(const CStack *Endangered) : endangered(Endangered)
  503. {
  504. sufferedDamage.fill(0);
  505. for(const CStack *enemy : cbc->battleGetStacks())
  506. {
  507. //Consider only stacks of different owner
  508. if(enemy->attackerOwned == endangered->attackerOwned)
  509. continue;
  510. //Look-up which tiles can be melee-attacked
  511. std::array<bool, GameConstants::BFIELD_SIZE> meleeAttackable;
  512. meleeAttackable.fill(false);
  513. auto enemyReachability = cbc->getReachability(enemy);
  514. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  515. {
  516. if(enemyReachability.isReachable(i))
  517. {
  518. meleeAttackable[i] = true;
  519. for(auto n : BattleHex(i).neighbouringTiles())
  520. meleeAttackable[n] = true;
  521. }
  522. }
  523. //Gather possible assaults
  524. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  525. {
  526. if(cbc->battleCanShoot(enemy, i))
  527. threatMap[i].push_back(BattleAttackInfo(enemy, endangered, true));
  528. else if(meleeAttackable[i])
  529. {
  530. BattleAttackInfo bai(enemy, endangered, false);
  531. bai.chargedFields = std::max(BattleHex::getDistance(enemy->position, i) - 1, 0); //TODO check real distance (BFS), not just metric
  532. threatMap[i].push_back(BattleAttackInfo(bai));
  533. }
  534. }
  535. }
  536. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  537. {
  538. sufferedDamage[i] = sum(threatMap[i], [](const BattleAttackInfo &bai) -> int
  539. {
  540. auto dmg = cbc->calculateDmgRange(bai);
  541. return (dmg.first + dmg.second)/2;
  542. });
  543. }
  544. }
  545. const TBonusListPtr StackWithBonuses::getAllBonuses(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root /*= nullptr*/, const std::string &cachingStr /*= ""*/) const
  546. {
  547. TBonusListPtr ret = std::make_shared<BonusList>();
  548. const TBonusListPtr originalList = stack->getAllBonuses(selector, limit, root, cachingStr);
  549. range::copy(*originalList, std::back_inserter(*ret));
  550. for(auto &bonus : bonusesToAdd)
  551. {
  552. auto b = std::make_shared<Bonus>(bonus);
  553. if(selector(b.get()) && (!limit || !limit(b.get())))
  554. ret->push_back(b);
  555. }
  556. //TODO limiters?
  557. return ret;
  558. }
  559. int AttackPossibility::damageDiff() const
  560. {
  561. if (!priorities)
  562. priorities = new Priorities;
  563. const auto dealtDmgValue = priorities->stackEvaluator(enemy) * damageDealt;
  564. const auto receivedDmgValue = priorities->stackEvaluator(attack.attacker) * damageReceived;
  565. return dealtDmgValue - receivedDmgValue;
  566. }
  567. int AttackPossibility::attackValue() const
  568. {
  569. return damageDiff() + tacticImpact;
  570. }
  571. AttackPossibility AttackPossibility::evaluate(const BattleAttackInfo &AttackInfo, const HypotheticChangesToBattleState &state, BattleHex hex)
  572. {
  573. auto attacker = AttackInfo.attacker;
  574. auto enemy = AttackInfo.defender;
  575. const int remainingCounterAttacks = getValOr(state.counterAttacksLeft, enemy, enemy->counterAttacksRemaining());
  576. const bool counterAttacksBlocked = attacker->hasBonusOfType(Bonus::BLOCKS_RETALIATION) || enemy->hasBonusOfType(Bonus::NO_RETALIATION);
  577. 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();
  578. AttackPossibility ap = {enemy, hex, AttackInfo, 0, 0, 0};
  579. auto curBai = AttackInfo; //we'll modify here the stack counts
  580. for(int i = 0; i < totalAttacks; i++)
  581. {
  582. std::pair<ui32, ui32> retaliation(0,0);
  583. auto attackDmg = cbc->battleEstimateDamage(CRandomGenerator::getDefault(), curBai, &retaliation);
  584. ap.damageDealt = (attackDmg.first + attackDmg.second) / 2;
  585. ap.damageReceived = (retaliation.first + retaliation.second) / 2;
  586. if(remainingCounterAttacks <= i || counterAttacksBlocked)
  587. ap.damageReceived = 0;
  588. curBai.attackerCount = attacker->count - attacker->countKilledByAttack(ap.damageReceived).first;
  589. curBai.defenderCount = enemy->count - enemy->countKilledByAttack(ap.damageDealt).first;
  590. if(!curBai.attackerCount)
  591. break;
  592. //TODO what about defender? should we break? but in pessimistic scenario defender might be alive
  593. }
  594. //TODO other damage related to attack (eg. fire shield and other abilities)
  595. //Limit damages by total stack health
  596. vstd::amin(ap.damageDealt, enemy->count * enemy->MaxHealth() - (enemy->MaxHealth() - enemy->firstHPleft));
  597. vstd::amin(ap.damageReceived, attacker->count * attacker->MaxHealth() - (attacker->MaxHealth() - attacker->firstHPleft));
  598. return ap;
  599. }
  600. PotentialTargets::PotentialTargets(const CStack *attacker, const HypotheticChangesToBattleState &state /*= HypotheticChangesToBattleState()*/)
  601. {
  602. auto dists = cbc->battleGetDistances(attacker);
  603. auto avHexes = cbc->battleGetAvailableHexes(attacker, false);
  604. for(const CStack *enemy : cbc->battleGetStacks())
  605. {
  606. //Consider only stacks of different owner
  607. if(enemy->attackerOwned == attacker->attackerOwned)
  608. continue;
  609. auto GenerateAttackInfo = [&](bool shooting, BattleHex hex) -> AttackPossibility
  610. {
  611. auto bai = BattleAttackInfo(attacker, enemy, shooting);
  612. bai.attackerBonuses = getValOr(state.bonusesOfStacks, bai.attacker, bai.attacker);
  613. bai.defenderBonuses = getValOr(state.bonusesOfStacks, bai.defender, bai.defender);
  614. if(hex.isValid())
  615. {
  616. assert(dists[hex] <= attacker->Speed());
  617. bai.chargedFields = dists[hex];
  618. }
  619. return AttackPossibility::evaluate(bai, state, hex);
  620. };
  621. if(cbc->battleCanShoot(attacker, enemy->position))
  622. {
  623. possibleAttacks.push_back(GenerateAttackInfo(true, BattleHex::INVALID));
  624. }
  625. else
  626. {
  627. for(BattleHex hex : avHexes)
  628. if(CStack::isMeleeAttackPossible(attacker, enemy, hex))
  629. possibleAttacks.push_back(GenerateAttackInfo(false, hex));
  630. if(!vstd::contains_if(possibleAttacks, [=](const AttackPossibility &pa) { return pa.enemy == enemy; }))
  631. unreachableEnemies.push_back(enemy);
  632. }
  633. }
  634. }
  635. AttackPossibility PotentialTargets::bestAction() const
  636. {
  637. if(possibleAttacks.empty())
  638. throw std::runtime_error("No best action, since we don't have any actions");
  639. return *vstd::maxElementByFun(possibleAttacks, [](const AttackPossibility &ap) { return ap.attackValue(); } );
  640. }
  641. int PotentialTargets::bestActionValue() const
  642. {
  643. if(possibleAttacks.empty())
  644. return 0;
  645. return bestAction().attackValue();
  646. }
  647. void EnemyInfo::calcDmg(const CStack * ourStack)
  648. {
  649. TDmgRange retal, dmg = cbc->battleEstimateDamage(CRandomGenerator::getDefault(), ourStack, s, &retal);
  650. adi = (dmg.first + dmg.second) / 2;
  651. adr = (retal.first + retal.second) / 2;
  652. }