2
0

BattleAI.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  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. const CBattleAI *ai;
  12. template<class ForwardRange, class ValueFunction>
  13. auto maxElementByFun(const ForwardRange& rng, ValueFunction vf) -> decltype(boost::begin(rng))
  14. {
  15. std::map<double, decltype(boost::begin(rng))> elements;
  16. for(auto i = boost::begin(rng); i != boost::end(rng); i++)
  17. elements[vf(*i)] = i;
  18. return (--(elements.end()))->second;
  19. }
  20. #define LOGL(text) print(text)
  21. #define LOGFL(text, formattingEl) print(boost::str(boost::format(text) % formattingEl))
  22. struct Priorities
  23. {
  24. double manaValue;
  25. double generalResourceValueModifier;
  26. std::vector<double> resourceTypeBaseValues;
  27. std::function<double(const CStack *)> stackEvaluator;
  28. Priorities()
  29. {
  30. manaValue = 0.;
  31. generalResourceValueModifier = 1.;
  32. range::copy(VLC->objh->resVals, std::back_inserter(resourceTypeBaseValues));
  33. stackEvaluator = [](const CStack*){ return 1.0; };
  34. }
  35. } priorities;
  36. int distToNearestNeighbour(BattleHex hex, const ReachabilityInfo::TDistances& dists, BattleHex *chosenHex = NULL)
  37. {
  38. int ret = 1000000;
  39. BOOST_FOREACH(BattleHex n, hex.neighbouringTiles())
  40. {
  41. if(dists[n] >= 0 && dists[n] < ret)
  42. {
  43. ret = dists[n];
  44. if(chosenHex)
  45. *chosenHex = n;
  46. }
  47. }
  48. return ret;
  49. }
  50. bool isCloser(const EnemyInfo & ei1, const EnemyInfo & ei2, const ReachabilityInfo::TDistances & dists)
  51. {
  52. return distToNearestNeighbour(ei1.s->position, dists) < distToNearestNeighbour(ei2.s->position, dists);
  53. }
  54. template <typename Container, typename Pred>
  55. auto sum(const Container & c, Pred p) -> decltype(p(*boost::begin(c)))
  56. {
  57. double ret = 0;
  58. BOOST_FOREACH(const auto &element, c)
  59. {
  60. ret += p(element);
  61. }
  62. return ret;
  63. }
  64. CBattleAI::CBattleAI(void)
  65. : side(-1)
  66. {
  67. print("created");
  68. }
  69. CBattleAI::~CBattleAI(void)
  70. {
  71. print("destroyed");
  72. if(cb)
  73. {
  74. //Restore previous state of CB - it may be shared with the main AI (like VCAI)
  75. cb->waitTillRealize = wasWaitingForRealize;
  76. cb->unlockGsWhenWaiting = wasUnlockingGs;
  77. }
  78. }
  79. void CBattleAI::init(shared_ptr<CBattleCallback> CB)
  80. {
  81. print("init called, saving ptr to IBattleCallback");
  82. cbc = cb = CB;
  83. playerID = *CB->getPlayerID();; //TODO should be sth in callback
  84. wasWaitingForRealize = cb->waitTillRealize;
  85. wasUnlockingGs = CB->unlockGsWhenWaiting;
  86. CB->waitTillRealize = true;
  87. CB->unlockGsWhenWaiting = false;
  88. }
  89. static bool thereRemainsEnemy()
  90. {
  91. return cbc->battleGetStacks(CBattleInfoEssentials::ONLY_ENEMY).size();
  92. }
  93. BattleAction CBattleAI::activeStack( const CStack * stack )
  94. {
  95. LOG_TRACE_PARAMS(logAi, "stack: %s", stack->nodeName()) ;
  96. cbc = cb; //TODO: make solid sure that AIs always use their callbacks (need to take care of event handlers too)
  97. ai = this;
  98. try
  99. {
  100. print("activeStack called for " + stack->nodeName());
  101. if(stack->type->idNumber == CreatureID::CATAPULT)
  102. return useCatapult(stack);
  103. print("Evaluating tactic situation...");
  104. tacticInfo = make_unique<TacticInfo>();
  105. print("Done!");
  106. if(cb->battleCanCastSpell())
  107. attemptCastingSpell();
  108. if(!thereRemainsEnemy())
  109. return BattleAction();
  110. if(auto action = considerFleeingOrSurrendering())
  111. return *action;
  112. if(cb->battleGetStacks(CBattleInfoEssentials::ONLY_ENEMY).empty())
  113. {
  114. //We apparently won battle by casting spell, return defend... (accessing cb may cause trouble)
  115. return BattleAction::makeDefend(stack);
  116. }
  117. PotentialTargets targets(stack);
  118. if(targets.possibleAttacks.size())
  119. {
  120. auto hlp = targets.bestAction();
  121. if(hlp.attack.shooting)
  122. return BattleAction::makeShotAttack(stack, hlp.enemy);
  123. else
  124. return BattleAction::makeMeleeAttack(stack, hlp.enemy, hlp.tile);
  125. }
  126. else
  127. {
  128. if(stack->waited())
  129. {
  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. BOOST_FOREACH(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. BOOST_FOREACH(auto &p, ourAttacks)
  310. ourPotential += p.second.bestAction().attackValue();
  311. BOOST_FOREACH(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. BOOST_FOREACH(auto spell, possibleSpells)
  349. {
  350. BOOST_FOREACH(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. auto evaluateSpellcast = [&] (const PossibleSpellcast &ps) -> int
  360. {
  361. const int skillLevel = hero->getSpellSchoolLevel(ps.spell);
  362. const int spellPower = hero->getPrimSkillLevel(PrimarySkill::SPELL_POWER);
  363. switch(spellType(ps.spell))
  364. {
  365. case OFFENSIVE_SPELL:
  366. {
  367. int damageDealt = 0, damageReceived = 0;
  368. auto stacksSuffering = cb->getAffectedCreatures(ps.spell, skillLevel, playerID, ps.dest);
  369. vstd::erase_if(stacksSuffering, [&](const CStack *stack) -> bool
  370. {
  371. return cb->battleIsImmune(hero, ps.spell, ECastingMode::HERO_CASTING, ps.dest);
  372. });
  373. if(stacksSuffering.empty())
  374. return -1;
  375. BOOST_FOREACH(auto stack, stacksSuffering)
  376. {
  377. const int dmg = cb->calculateSpellDmg(ps.spell, hero, stack, skillLevel, spellPower);
  378. if(stack->owner == playerID)
  379. damageReceived += priorities.stackEvaluator(stack) * dmg;
  380. else
  381. damageDealt += priorities.stackEvaluator(stack) * dmg;
  382. }
  383. const int damageDiff = damageDealt - damageReceived;
  384. LOGFL("Casting %s on hex %d would deal %d damage points among %d stacks.",
  385. ps.spell->name % ps.dest % damageDiff % stacksSuffering.size());
  386. return damageDiff;
  387. }
  388. case TIMED_EFFECT:
  389. {
  390. auto affectedCreatures = cb->getAffectedCreatures(ps.spell, skillLevel, playerID, ps.dest);
  391. if(affectedCreatures.empty())
  392. return -1;
  393. int baseValue = 0;
  394. BOOST_FOREACH(auto &affectedStack, affectedCreatures)
  395. {
  396. StackWithBonuses swb;
  397. swb.stack = affectedStack;
  398. Bonus pseudoBonus;
  399. pseudoBonus.sid = ps.spell->id;
  400. pseudoBonus.val = skillLevel;
  401. pseudoBonus.turnsRemain = 1; //TODO
  402. CStack::stackEffectToFeature(swb.bonusesToAdd, pseudoBonus);
  403. HypotheticChangesToBattleState state;
  404. state.bonusesOfStacks[swb.stack] = &swb;
  405. PotentialTargets pt(swb.stack, state);
  406. auto newValue = pt.bestActionValue();
  407. auto oldValue = tacticInfo->targets[swb.stack].bestActionValue();
  408. auto gain = newValue - oldValue;
  409. if(swb.stack->owner != playerID) //enemy
  410. gain = -gain;
  411. baseValue += gain;
  412. LOGFL("Casting %s on %s would improve the stack by %d points (from %d to %d)",
  413. ps.spell->name % swb.stack->nodeName() % gain % (oldValue) % (newValue));
  414. }
  415. const int time = std::min(spellPower, tacticInfo->expectedLength());
  416. int ret = 0;
  417. for(int i = 0; i < time; i++)
  418. ret += (baseValue>>i);
  419. LOGFL("Spell %s has base value of %d, will last %d turns of which %d is useful. Total value: %d.",
  420. ps.spell->name % baseValue % spellPower % time % ret);
  421. return ret;
  422. }
  423. default:
  424. assert(0);
  425. return 0;
  426. }
  427. };
  428. const auto castToPerform = *maxElementByFun(possibleCasts, evaluateSpellcast);
  429. const double spellValue = evaluateSpellcast(castToPerform);
  430. const double spellCost = priorities.manaValue * cb->battleGetSpellCost(castToPerform.spell, hero);
  431. LOGFL("Best spell is %s. Value is %d, cost %s.", castToPerform.spell->name % spellValue % spellCost);
  432. if(spellValue >= spellCost)
  433. {
  434. LOGL("Will cast the spell.");
  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. else
  444. {
  445. LOGL("Won't cast the spell.");
  446. return;
  447. }
  448. }
  449. std::vector<BattleHex> CBattleAI::getTargetsToConsider( const CSpell *spell ) const
  450. {
  451. if(spell->getTargetType() == CSpell::NO_TARGET)
  452. {
  453. //Spell can be casted anywhere, all hexes are potentially considerable.
  454. std::vector<BattleHex> ret;
  455. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  456. if(BattleHex(i).isAvailable())
  457. ret.push_back(i);
  458. return ret;
  459. }
  460. else
  461. {
  462. //TODO when massive effect -> doesnt matter where cast
  463. return cbc->battleGetPossibleTargets(playerID, spell);
  464. }
  465. }
  466. boost::optional<BattleAction> CBattleAI::considerFleeingOrSurrendering()
  467. {
  468. if(cb->battleCanSurrender(playerID))
  469. {
  470. }
  471. if(cb->battleCanFlee())
  472. {
  473. }
  474. return boost::none;
  475. }
  476. ThreatMap::ThreatMap(const CStack *Endangered) : endangered(Endangered)
  477. {
  478. sufferedDamage.fill(0);
  479. BOOST_FOREACH(const CStack *enemy, cbc->battleGetStacks())
  480. {
  481. //Consider only stacks of different owner
  482. if(enemy->attackerOwned == endangered->attackerOwned)
  483. continue;
  484. //Look-up which tiles can be melee-attacked
  485. std::array<bool, GameConstants::BFIELD_SIZE> meleeAttackable;
  486. meleeAttackable.fill(false);
  487. auto enemyReachability = cbc->getReachability(enemy);
  488. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  489. {
  490. if(enemyReachability.isReachable(i))
  491. {
  492. meleeAttackable[i] = true;
  493. BOOST_FOREACH(auto n, BattleHex(i).neighbouringTiles())
  494. meleeAttackable[n] = true;
  495. }
  496. }
  497. //Gather possible assaults
  498. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  499. {
  500. if(cbc->battleCanShoot(enemy, i))
  501. threatMap[i].push_back(BattleAttackInfo(enemy, endangered, true));
  502. else if(meleeAttackable[i])
  503. {
  504. BattleAttackInfo bai(enemy, endangered, false);
  505. bai.chargedFields = std::max(BattleHex::getDistance(enemy->position, i) - 1, 0); //TODO check real distance (BFS), not just metric
  506. threatMap[i].push_back(BattleAttackInfo(bai));
  507. }
  508. }
  509. }
  510. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  511. {
  512. sufferedDamage[i] = sum(threatMap[i], [](const BattleAttackInfo &bai) -> int
  513. {
  514. auto dmg = cbc->calculateDmgRange(bai);
  515. return (dmg.first + dmg.second)/2;
  516. });
  517. }
  518. }
  519. const TBonusListPtr StackWithBonuses::getAllBonuses(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root /*= NULL*/, const std::string &cachingStr /*= ""*/) const
  520. {
  521. TBonusListPtr ret = make_shared<BonusList>();
  522. const TBonusListPtr originalList = stack->getAllBonuses(selector, limit, root, cachingStr);
  523. boost::copy(*originalList, std::back_inserter(*ret));
  524. BOOST_FOREACH(auto &bonus, bonusesToAdd)
  525. {
  526. if(selector(&bonus) && (!limit || !limit(&bonus)))
  527. ret->push_back(&bonus);
  528. }
  529. //TODO limiters?
  530. return ret;
  531. }
  532. int AttackPossibility::damageDiff() const
  533. {
  534. const auto dealtDmgValue = priorities.stackEvaluator(enemy) * damageDealt;
  535. const auto receivedDmgValue = priorities.stackEvaluator(attack.attacker) * damageReceived;
  536. return dealtDmgValue - receivedDmgValue;
  537. }
  538. int AttackPossibility::attackValue() const
  539. {
  540. return damageDiff() /*+ tacticImpact*/;
  541. }
  542. AttackPossibility AttackPossibility::evaluate(const BattleAttackInfo &AttackInfo, const HypotheticChangesToBattleState &state, BattleHex hex)
  543. {
  544. auto attacker = AttackInfo.attacker;
  545. auto defender = AttackInfo.defender;
  546. const int initialAttackerCount = getValOr(state.stackCount, attacker, attacker->count);
  547. const int initialDefenderCount = getValOr(state.stackCount, defender, defender->count);
  548. const int remainingCounterAttacks = getValOr(state.counterAttacksLeft, defender, defender->counterAttacks);
  549. const bool counterAttacksBlocked = attacker->hasBonusOfType(Bonus::BLOCKS_RETALIATION) || defender->hasBonusOfType(Bonus::NO_RETALIATION);
  550. const int totalAttacks = 1 + AttackInfo.attackerBonuses->getBonuses(Selector::type(Bonus::ADDITIONAL_ATTACK), (Selector::effectRange (Bonus::NO_LIMIT) || Selector::effectRange(Bonus::ONLY_MELEE_FIGHT)))->totalValue();
  551. AttackPossibility ap = {defender, hex, AttackInfo, 0, 0/*, 0*/};
  552. auto curBai = AttackInfo; //we'll modify here the stack counts
  553. for(int i = 0; i < totalAttacks; i++)
  554. {
  555. std::pair<ui32, ui32> retaliation(0,0);
  556. auto attackDmg = cbc->battleEstimateDamage(curBai, &retaliation);
  557. ap.damageDealt = (attackDmg.first + attackDmg.second) / 2;
  558. ap.damageReceived = (retaliation.first + retaliation.second) / 2;
  559. if(remainingCounterAttacks <= i || counterAttacksBlocked)
  560. ap.damageReceived = 0;
  561. curBai.attackerCount = initialAttackerCount - attacker->countKilledByAttack(ap.damageReceived).first;
  562. curBai.defenderCount = initialDefenderCount - defender->countKilledByAttack(ap.damageDealt).first;
  563. if(!curBai.attackerCount)
  564. break;
  565. //TODO what about defender? should we break? but in pessimistic scenario defender might be alive
  566. }
  567. //TODO LUCK!!!!!!!!!!!!
  568. //TODO other damage related to attack (eg. fire shield and other abilities)
  569. //Limit damages by total stack health
  570. vstd::amin(ap.damageDealt, initialDefenderCount * defender->MaxHealth() - (defender->MaxHealth() - defender->firstHPleft));
  571. vstd::amin(ap.damageReceived, initialAttackerCount * attacker->MaxHealth() - (attacker->MaxHealth() - attacker->firstHPleft));
  572. return ap;
  573. }
  574. PotentialTargets::PotentialTargets(const CStack *attacker, const HypotheticChangesToBattleState &state /*= HypotheticChangesToBattleState()*/)
  575. {
  576. auto dists = cbc->battleGetDistances(attacker);
  577. auto avHexes = cbc->battleGetAvailableHexes(attacker, false);
  578. BOOST_FOREACH(const CStack *enemy, cbc->battleGetStacks())
  579. {
  580. //Consider only stacks of different owner
  581. if(enemy->attackerOwned == attacker->attackerOwned)
  582. continue;
  583. auto GenerateAttackInfo = [&](bool shooting, BattleHex hex) -> AttackPossibility
  584. {
  585. auto bai = BattleAttackInfo(attacker, enemy, shooting);
  586. bai.attackerBonuses = getValOr(state.bonusesOfStacks, bai.attacker, bai.attacker);
  587. bai.defenderBonuses = getValOr(state.bonusesOfStacks, bai.defender, bai.defender);
  588. if(hex.isValid())
  589. {
  590. assert(dists[hex] <= attacker->Speed());
  591. bai.chargedFields = dists[hex];
  592. }
  593. return AttackPossibility::evaluate(bai, state, hex);
  594. };
  595. if(cbc->battleCanShoot(attacker, enemy->position))
  596. {
  597. possibleAttacks.push_back(GenerateAttackInfo(true, BattleHex::INVALID));
  598. }
  599. else
  600. {
  601. BOOST_FOREACH(BattleHex hex, avHexes)
  602. if(CStack::isMeleeAttackPossible(attacker, enemy, hex))
  603. possibleAttacks.push_back(GenerateAttackInfo(false, hex));
  604. if(!vstd::contains_if(possibleAttacks, [=](const AttackPossibility &pa) { return pa.enemy == enemy; }))
  605. unreachableEnemies.push_back(enemy);
  606. }
  607. }
  608. }
  609. AttackPossibility PotentialTargets::bestAction() const
  610. {
  611. if(possibleAttacks.empty())
  612. throw std::runtime_error("No best action, since we don't have any actions");
  613. return *maxElementByFun(possibleAttacks, [](const AttackPossibility &ap) { return ap.attackValue(); } );
  614. }
  615. int PotentialTargets::bestActionValue() const
  616. {
  617. if(possibleAttacks.empty())
  618. return 0;
  619. return bestAction().attackValue();
  620. }
  621. void EnemyInfo::calcDmg(const CStack * ourStack)
  622. {
  623. TDmgRange retal, dmg = cbc->battleEstimateDamage(ourStack, s, &retal);
  624. adi = (dmg.first + dmg.second) / 2;
  625. adr = (retal.first + retal.second) / 2;
  626. }
  627. TacticInfo::TacticInfo(const HypotheticChangesToBattleState &state /*= HypotheticChangesToBattleState()*/)
  628. {
  629. ourPotential = enemyPotential = ourHealth = enemyhealth = 0;
  630. BOOST_FOREACH(const CStack * ourStack, cbc->battleGetStacks(CBattleInfoEssentials::ONLY_MINE))
  631. {
  632. if(getValOr(state.stackCount, ourStack, ourStack->count) <= 0) continue;
  633. targets[ourStack] = PotentialTargets(ourStack, state);
  634. ourPotential += targets[ourStack].bestActionValue();
  635. ourHealth += (ourStack->count-1) * ourStack->MaxHealth() + ourStack->firstHPleft;
  636. }
  637. BOOST_FOREACH(const CStack * enemyStack, cbc->battleGetStacks(CBattleInfoEssentials::ONLY_ENEMY))
  638. {
  639. if(getValOr(state.stackCount, enemyStack, enemyStack->count) <= 0) continue;
  640. targets[enemyStack] = PotentialTargets(enemyStack, state);
  641. enemyPotential += targets[enemyStack].bestActionValue();
  642. enemyhealth += (enemyStack->count-1) * enemyStack->MaxHealth() + enemyStack->firstHPleft;
  643. }
  644. }
  645. double TacticInfo::totalValue() const
  646. {
  647. return ourPotential - enemyPotential;
  648. }
  649. int TacticInfo::expectedLength() const
  650. {
  651. double value = totalValue();
  652. if(value > 0)
  653. return std::ceil(enemyhealth / ourPotential);
  654. else if(value < 0)
  655. return std::ceil(ourHealth / enemyPotential);
  656. return 10000;
  657. }