BattleAI.cpp 22 KB

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