BattleAI.cpp 24 KB

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