BattleAI.cpp 17 KB

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