BattleAI.cpp 21 KB

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