BattleAI.cpp 22 KB

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