BattleAI.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  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. }
  59. void CBattleAI::init( CBattleCallback * CB )
  60. {
  61. print("init called, saving ptr to IBattleCallback");
  62. cbc = cb = CB;
  63. playerID = CB->getPlayerID();; //TODO should be sth in callback
  64. CB->waitTillRealize = true;
  65. CB->unlockGsWhenWaiting = false;
  66. }
  67. void CBattleAI::actionFinished( const BattleAction *action )
  68. {
  69. print("actionFinished called");
  70. }
  71. void CBattleAI::actionStarted( const BattleAction *action )
  72. {
  73. print("actionStarted called");
  74. }
  75. struct EnemyInfo
  76. {
  77. const CStack * s;
  78. int adi, adr;
  79. std::vector<BattleHex> attackFrom; //for melee fight
  80. EnemyInfo(const CStack * _s) : s(_s)
  81. {}
  82. void calcDmg(const CStack * ourStack)
  83. {
  84. TDmgRange retal, dmg = cbc->battleEstimateDamage(ourStack, s, &retal);
  85. adi = (dmg.first + dmg.second) / 2;
  86. adr = (retal.first + retal.second) / 2;
  87. }
  88. bool operator==(const EnemyInfo& ei) const
  89. {
  90. return s == ei.s;
  91. }
  92. };
  93. bool isMoreProfitable(const EnemyInfo &ei1, const EnemyInfo& ei2)
  94. {
  95. return (ei1.adi-ei1.adr) < (ei2.adi - ei2.adr);
  96. }
  97. int distToNearestNeighbour(BattleHex hex, const ReachabilityInfo::TDistances& dists, BattleHex *chosenHex = NULL)
  98. {
  99. int ret = 1000000;
  100. BOOST_FOREACH(BattleHex n, hex.neighbouringTiles())
  101. {
  102. if(dists[n] >= 0 && dists[n] < ret)
  103. {
  104. ret = dists[n];
  105. if(chosenHex)
  106. *chosenHex = n;
  107. }
  108. }
  109. return ret;
  110. }
  111. bool isCloser(const EnemyInfo & ei1, const EnemyInfo & ei2, const ReachabilityInfo::TDistances & dists)
  112. {
  113. return distToNearestNeighbour(ei1.s->position, dists) < distToNearestNeighbour(ei2.s->position, dists);
  114. }
  115. static bool willSecondHexBlockMoreEnemyShooters(const BattleHex &h1, const BattleHex &h2)
  116. {
  117. int shooters[2] = {0}; //count of shooters on hexes
  118. for(int i = 0; i < 2; i++)
  119. BOOST_FOREACH(BattleHex neighbour, (i ? h2 : h1).neighbouringTiles())
  120. if(const CStack *s = cbc->battleGetStackByPos(neighbour))
  121. if(s->getCreature()->isShooting())
  122. shooters[i]++;
  123. return shooters[0] < shooters[1];
  124. }
  125. template <typename Container, typename Pred>
  126. auto sum(const Container & c, Pred p) -> decltype(p(*boost::begin(c)))
  127. {
  128. double ret = 0;
  129. BOOST_FOREACH(const auto &element, c)
  130. {
  131. ret += p(element);
  132. }
  133. return ret;
  134. }
  135. struct ThreatMap
  136. {
  137. std::array<std::vector<BattleAttackInfo>, GameConstants::BFIELD_SIZE> threatMap; // [hexNr] -> enemies able to strike
  138. const CStack *endangered;
  139. std::array<int, GameConstants::BFIELD_SIZE> sufferedDamage;
  140. struct ThreatMap(const CStack *Endangered)
  141. : endangered(Endangered)
  142. {
  143. sufferedDamage.fill(0);
  144. BOOST_FOREACH(const CStack *enemy, cbc->battleGetStacks())
  145. {
  146. //Consider only stacks of different owner
  147. if(enemy->attackerOwned == endangered->attackerOwned)
  148. continue;
  149. //Look-up which tiles can be melee-attacked
  150. std::array<bool, GameConstants::BFIELD_SIZE> meleeAttackable;
  151. meleeAttackable.fill(false);
  152. auto enemyReachability = cbc->getReachability(enemy);
  153. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  154. {
  155. if(enemyReachability.isReachable(i))
  156. {
  157. meleeAttackable[i] = true;
  158. BOOST_FOREACH(auto n, BattleHex(i).neighbouringTiles())
  159. meleeAttackable[n] = true;
  160. }
  161. }
  162. //Gather possible assaults
  163. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  164. {
  165. if(cbc->battleCanShoot(enemy, i))
  166. threatMap[i].push_back(BattleAttackInfo(enemy, endangered, true));
  167. else if(meleeAttackable[i])
  168. {
  169. BattleAttackInfo bai(enemy, endangered, false);
  170. bai.chargedFields = std::max(BattleHex::getDistance(enemy->position, i) - 1, 0); //TODO check real distance (BFS), not just metric
  171. threatMap[i].push_back(BattleAttackInfo(bai));
  172. }
  173. }
  174. }
  175. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  176. {
  177. sufferedDamage[i] = sum(threatMap[i], [](const BattleAttackInfo &bai) -> int
  178. {
  179. auto dmg = cbc->calculateDmgRange(bai);
  180. return (dmg.first + dmg.second)/2;
  181. });
  182. }
  183. }
  184. };
  185. struct AttackPossibility
  186. {
  187. const CStack *enemy; //redundant (to attack.defender) but looks nice
  188. BattleHex tile; //tile from which we attack
  189. BattleAttackInfo attack;
  190. int damageDealt;
  191. int damageReceived; //usually by counter-attack
  192. int damageDiff() const
  193. {
  194. return damageDealt - damageReceived;
  195. }
  196. int attackValue() const
  197. {
  198. //TODO consider tactical advantage
  199. return damageDiff();
  200. }
  201. };
  202. struct PotentialTargets
  203. {
  204. std::vector<AttackPossibility> possibleAttacks;
  205. std::vector<const CStack *> unreachableEnemies;
  206. std::function<AttackPossibility(bool,BattleHex)> GenerateAttackInfo; //args: shooting, destHex
  207. PotentialTargets(const CStack *attacker, optional<IBonusBearer*> attackerBonuses = boost::none)
  208. {
  209. auto dists = cbc->battleGetDistances(attacker);
  210. std::vector<BattleHex> avHexes = cbc->battleGetAvailableHexes(attacker, false);
  211. BOOST_FOREACH(const CStack *enemy, cbc->battleGetStacks())
  212. {
  213. //Consider only stacks of different owner
  214. if(enemy->attackerOwned == attacker->attackerOwned)
  215. continue;
  216. GenerateAttackInfo = [&](bool shooting, BattleHex hex) -> AttackPossibility
  217. {
  218. auto bai = BattleAttackInfo(attacker, enemy, shooting);
  219. if(attackerBonuses)
  220. bai.attackerBonuses = *attackerBonuses;
  221. AttackPossibility ap = {enemy, hex, bai, 0, 0};
  222. if(hex.isValid())
  223. {
  224. assert(dists[hex] <= attacker->Speed());
  225. ap.attack.chargedFields = dists[hex];
  226. }
  227. std::pair<ui32, ui32> retaliation;
  228. auto attackDmg = cbc->battleEstimateDamage(ap.attack, &retaliation);
  229. ap.damageDealt = (attackDmg.first + attackDmg.second) / 2;
  230. ap.damageReceived = (retaliation.first + retaliation.second) / 2;
  231. //TODO other damage related to attack (eg. fire shield and other abilities)
  232. //TODO limit max damage by total stacks health (dealing 100000 dmg to single Pikineer is not that effective)
  233. return ap;
  234. };
  235. if(cbc->battleCanShoot(attacker, enemy->position))
  236. {
  237. possibleAttacks.push_back(GenerateAttackInfo(true, BattleHex::INVALID));
  238. }
  239. else
  240. {
  241. BOOST_FOREACH(BattleHex hex, avHexes)
  242. if(CStack::isMeleeAttackPossible(attacker, enemy, hex))
  243. possibleAttacks.push_back(GenerateAttackInfo(false, hex));
  244. if(!vstd::contains_if(possibleAttacks, [=](const AttackPossibility &pa) { return pa.enemy == enemy; }))
  245. unreachableEnemies.push_back(enemy);
  246. }
  247. }
  248. }
  249. AttackPossibility bestAction() const
  250. {
  251. if(possibleAttacks.empty())
  252. throw std::runtime_error("No best action, since we don't have any actions");
  253. return *vstd::maxElementByFun(possibleAttacks, [](const AttackPossibility &ap) { return ap.damageDiff(); } );
  254. }
  255. };
  256. BattleAction CBattleAI::activeStack( const CStack * stack )
  257. {
  258. try
  259. {
  260. print("activeStack called for " + stack->nodeName());
  261. if(stack->type->idNumber == 145) //catapult
  262. return useCatapult(stack);
  263. if(cb->battleCanCastSpell())
  264. attemptCastingSpell();
  265. ThreatMap threatsToUs(stack);
  266. PotentialTargets targets(stack);
  267. if(targets.possibleAttacks.size())
  268. {
  269. auto hlp = targets.bestAction();
  270. if(hlp.attack.shooting)
  271. return BattleAction::makeShotAttack(stack, hlp.enemy);
  272. else
  273. return BattleAction::makeMeleeAttack(stack, hlp.enemy, hlp.tile);
  274. }
  275. else
  276. {
  277. if(stack->waited())
  278. {
  279. auto dists = cbc->battleGetDistances(stack);
  280. const EnemyInfo &ei= *range::min_element(targets.unreachableEnemies, boost::bind(isCloser, _1, _2, boost::ref(dists)));
  281. if(distToNearestNeighbour(ei.s->position, dists) < GameConstants::BFIELD_SIZE)
  282. {
  283. return goTowards(stack, ei.s->position);
  284. }
  285. }
  286. else
  287. {
  288. return BattleAction::makeWait(stack);
  289. }
  290. }
  291. }
  292. catch(std::exception &e)
  293. {
  294. tlog1 << "Exception occurred in " << __FUNCTION__ << " " << e.what() << std::endl;
  295. }
  296. return BattleAction::makeDefend(stack);
  297. }
  298. void CBattleAI::battleAttack(const BattleAttack *ba)
  299. {
  300. print("battleAttack called");
  301. }
  302. void CBattleAI::battleStacksAttacked(const std::vector<BattleStackAttacked> & bsa)
  303. {
  304. print("battleStacksAttacked called");
  305. }
  306. void CBattleAI::battleEnd(const BattleResult *br)
  307. {
  308. print("battleEnd called");
  309. }
  310. void CBattleAI::battleNewRoundFirst(int round)
  311. {
  312. print("battleNewRoundFirst called");
  313. }
  314. void CBattleAI::battleNewRound(int round)
  315. {
  316. print("battleNewRound called");
  317. }
  318. void CBattleAI::battleStackMoved(const CStack * stack, std::vector<BattleHex> dest, int distance)
  319. {
  320. print("battleStackMoved called");;
  321. }
  322. void CBattleAI::battleSpellCast(const BattleSpellCast *sc)
  323. {
  324. print("battleSpellCast called");
  325. }
  326. void CBattleAI::battleStacksEffectsSet(const SetStackEffect & sse)
  327. {
  328. print("battleStacksEffectsSet called");
  329. }
  330. void CBattleAI::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool Side)
  331. {
  332. print("battleStart called");
  333. side = Side;
  334. }
  335. void CBattleAI::battleStacksHealedRes(const std::vector<std::pair<ui32, ui32> > & healedStacks, bool lifeDrain, bool tentHeal, si32 lifeDrainFrom)
  336. {
  337. print("battleStacksHealedRes called");
  338. }
  339. void CBattleAI::battleNewStackAppeared(const CStack * stack)
  340. {
  341. print("battleNewStackAppeared called");
  342. }
  343. void CBattleAI::battleObstaclesRemoved(const std::set<si32> & removedObstacles)
  344. {
  345. print("battleObstaclesRemoved called");
  346. }
  347. void CBattleAI::battleCatapultAttacked(const CatapultAttack & ca)
  348. {
  349. print("battleCatapultAttacked called");
  350. }
  351. void CBattleAI::battleStacksRemoved(const BattleStacksRemoved & bsr)
  352. {
  353. print("battleStacksRemoved called");
  354. }
  355. void CBattleAI::print(const std::string &text) const
  356. {
  357. tlog6 << "CBattleAI [" << this <<"]: " << text << std::endl;
  358. }
  359. BattleAction CBattleAI::goTowards(const CStack * stack, BattleHex destination)
  360. {
  361. assert(destination.isValid());
  362. auto avHexes = cb->battleGetAvailableHexes(stack, false);
  363. auto reachability = cb->getReachability(stack);
  364. if(vstd::contains(avHexes, destination))
  365. return BattleAction::makeMove(stack, destination);
  366. auto destNeighbours = destination.neighbouringTiles();
  367. if(vstd::contains_if(destNeighbours, [&](BattleHex n) { return stack->coversPos(destination); }))
  368. {
  369. tlog3 << "Warning: already standing on neighbouring tile!" << std::endl;
  370. //We shouldn't even be here...
  371. return BattleAction::makeDefend(stack);
  372. }
  373. vstd::erase_if(destNeighbours, [&](BattleHex hex){ return !reachability.accessibility.accessible(hex, stack); });
  374. if(!avHexes.size() || !destNeighbours.size()) //we are blocked or dest is blocked
  375. {
  376. print("goTowards: Stack cannot move! That's " + stack->nodeName());
  377. return BattleAction::makeDefend(stack);
  378. }
  379. if(stack->hasBonusOfType(Bonus::FLYING))
  380. {
  381. // Flying stack doesn't go hex by hex, so we can't backtrack using predecessors.
  382. // We just check all available hexes and pick the one closest to the target.
  383. auto distToDestNeighbour = [&](BattleHex hex) -> int
  384. {
  385. auto nearestNeighbourToHex = vstd::minElementByFun(destNeighbours, [&](BattleHex a)
  386. {
  387. return BattleHex::getDistance(a, hex);
  388. });
  389. return BattleHex::getDistance(*nearestNeighbourToHex, hex);
  390. };
  391. auto nearestAvailableHex = vstd::minElementByFun(avHexes, distToDestNeighbour);
  392. return BattleAction::makeMove(stack, *nearestAvailableHex);
  393. }
  394. else
  395. {
  396. BattleHex bestNeighbor = destination;
  397. if(distToNearestNeighbour(destination, reachability.distances, &bestNeighbor) > GameConstants::BFIELD_SIZE)
  398. {
  399. print("goTowards: Cannot reach");
  400. return BattleAction::makeDefend(stack);
  401. }
  402. BattleHex currentDest = bestNeighbor;
  403. while(1)
  404. {
  405. assert(currentDest.isValid());
  406. if(vstd::contains(avHexes, currentDest))
  407. return BattleAction::makeMove(stack, currentDest);
  408. currentDest = reachability.predecessors[currentDest];
  409. }
  410. }
  411. }
  412. BattleAction CBattleAI::useCatapult(const CStack * stack)
  413. {
  414. throw std::exception("The method or operation is not implemented.");
  415. }
  416. bool isSupportedSpell(const CSpell *spell)
  417. {
  418. switch(spell->id)
  419. {
  420. // permanent effects
  421. case Spells::SHIELD:
  422. case Spells::AIR_SHIELD:
  423. case Spells::FIRE_SHIELD:
  424. case Spells::PROTECTION_FROM_AIR:
  425. case Spells::PROTECTION_FROM_FIRE:
  426. case Spells::PROTECTION_FROM_WATER:
  427. case Spells::PROTECTION_FROM_EARTH:
  428. case Spells::ANTI_MAGIC:
  429. case Spells::MAGIC_MIRROR:
  430. case Spells::BLESS:
  431. case Spells::CURSE:
  432. case Spells::BLOODLUST:
  433. case Spells::PRECISION:
  434. case Spells::WEAKNESS:
  435. case Spells::STONE_SKIN:
  436. case Spells::DISRUPTING_RAY:
  437. case Spells::PRAYER:
  438. case Spells::MIRTH:
  439. case Spells::SORROW:
  440. case Spells::FORTUNE:
  441. case Spells::MISFORTUNE:
  442. case Spells::HASTE:
  443. case Spells::SLOW:
  444. case Spells::SLAYER:
  445. case Spells::FRENZY:
  446. case Spells::COUNTERSTRIKE:
  447. case Spells::BERSERK:
  448. case Spells::HYPNOTIZE:
  449. case Spells::FORGETFULNESS:
  450. case Spells::BLIND:
  451. case Spells::STONE_GAZE:
  452. case Spells::POISON:
  453. case Spells::BIND:
  454. case Spells::DISEASE:
  455. case Spells::PARALYZE:
  456. case Spells::AGE:
  457. case Spells::ACID_BREATH_DEFENSE:
  458. return true;
  459. default:
  460. return false;
  461. }
  462. };
  463. struct PossibleSpellcast
  464. {
  465. const CSpell *spell;
  466. BattleHex dest;
  467. };
  468. void CBattleAI::attemptCastingSpell()
  469. {
  470. LOGL("Casting spells sounds like fun. Let's see...");
  471. auto known = cb->battleGetFightingHero(side);
  472. //Get all spells we can cast
  473. std::vector<const CSpell*> possibleSpells;
  474. vstd::copy_if(VLC->spellh->spells, std::back_inserter(possibleSpells), [this] (const CSpell *s) -> bool
  475. {
  476. auto problem = cbc->battleCanCastThisSpell(s);
  477. return problem == ESpellCastProblem::OK;
  478. });
  479. LOGFL("I can cast %d spells.", possibleSpells.size());
  480. vstd::erase_if(possibleSpells, [](const CSpell *s)
  481. {return !isSupportedSpell(s); });
  482. LOGFL("I know about workings of %d of them.", possibleSpells.size());
  483. //Get possible spell-target pairs
  484. std::vector<PossibleSpellcast> possibleCasts;
  485. BOOST_FOREACH(auto spell, possibleSpells)
  486. {
  487. BOOST_FOREACH(auto hex, cbc->battleGetPossibleTargets(playerID, spell))
  488. {
  489. PossibleSpellcast ps = {spell, hex};
  490. possibleCasts.push_back(ps);
  491. }
  492. }
  493. LOGFL("Found %d spell-target combinations.", possibleCasts.size());
  494. if(possibleCasts.empty())
  495. return;
  496. std::map<const CStack*, int> valueOfStack;
  497. BOOST_FOREACH(auto stack, cb->battleGetStacks())
  498. {
  499. PotentialTargets pt(stack);
  500. valueOfStack[stack] = pt.bestAction().attackValue();
  501. }
  502. auto evaluateSpellcast = [&] (const PossibleSpellcast &ps) -> int
  503. {
  504. int skillLevel = 0;
  505. StackWithBonuses swb;
  506. swb.stack = cb->battleGetStackByPos(ps.dest);
  507. if(!swb.stack)
  508. return -1;
  509. Bonus pseudoBonus;
  510. pseudoBonus.sid = ps.spell->id;
  511. pseudoBonus.val = skillLevel;
  512. pseudoBonus.turnsRemain = 1; //TODO
  513. CStack::stackEffectToFeature(swb.bonusesToAdd, pseudoBonus);
  514. PotentialTargets pt(swb.stack, &swb);
  515. auto newValue = pt.bestAction().attackValue();
  516. auto oldValue = valueOfStack[swb.stack];
  517. auto gain = newValue - oldValue;
  518. if(swb.stack->owner != playerID) //enemy
  519. gain = -gain;
  520. LOGFL("Casting %s on %s would improve the stack by %d points (from %d to %d)",
  521. ps.spell->name % swb.stack->nodeName() % gain % (oldValue) % (newValue));
  522. return gain;
  523. };
  524. auto castToPerform = *vstd::maxElementByFun(possibleCasts, evaluateSpellcast);
  525. BattleAction spellcast;
  526. spellcast.actionType = BattleAction::HERO_SPELL;
  527. spellcast.additionalInfo = castToPerform.spell->id;
  528. spellcast.destinationTile = castToPerform.dest;
  529. spellcast.side = side;
  530. spellcast.stackNumber = (!side) ? -1 : -2;
  531. cb->battleMakeAction(&spellcast);
  532. }