BattleAI.cpp 21 KB

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