BattleAI.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. /*
  2. * BattleAI.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "BattleAI.h"
  12. #include "StackWithBonuses.h"
  13. #include "EnemyInfo.h"
  14. #include "../../lib/spells/CSpellHandler.h"
  15. #define LOGL(text) print(text)
  16. #define LOGFL(text, formattingEl) print(boost::str(boost::format(text) % formattingEl))
  17. CBattleAI::CBattleAI(void)
  18. : side(-1), wasWaitingForRealize(false), wasUnlockingGs(false)
  19. {
  20. }
  21. CBattleAI::~CBattleAI(void)
  22. {
  23. if(cb)
  24. {
  25. //Restore previous state of CB - it may be shared with the main AI (like VCAI)
  26. cb->waitTillRealize = wasWaitingForRealize;
  27. cb->unlockGsWhenWaiting = wasUnlockingGs;
  28. }
  29. }
  30. void CBattleAI::init(std::shared_ptr<CBattleCallback> CB)
  31. {
  32. setCbc(CB);
  33. cb = CB;
  34. playerID = *CB->getPlayerID();; //TODO should be sth in callback
  35. wasWaitingForRealize = cb->waitTillRealize;
  36. wasUnlockingGs = CB->unlockGsWhenWaiting;
  37. CB->waitTillRealize = true;
  38. CB->unlockGsWhenWaiting = false;
  39. }
  40. BattleAction CBattleAI::activeStack( const CStack * stack )
  41. {
  42. LOG_TRACE_PARAMS(logAi, "stack: %s", stack->nodeName()) ;
  43. setCbc(cb); //TODO: make solid sure that AIs always use their callbacks (need to take care of event handlers too)
  44. try
  45. {
  46. if(stack->type->idNumber == CreatureID::CATAPULT)
  47. return useCatapult(stack);
  48. if(stack->hasBonusOfType(Bonus::SIEGE_WEAPON) && stack->hasBonusOfType(Bonus::HEALER))
  49. {
  50. auto healingTargets = cb->battleGetStacks(CBattleInfoEssentials::ONLY_MINE);
  51. std::map<int, const CStack*> woundHpToStack;
  52. for(auto stack : healingTargets)
  53. if(auto woundHp = stack->MaxHealth() - stack->firstHPleft)
  54. woundHpToStack[woundHp] = stack;
  55. if(woundHpToStack.empty())
  56. return BattleAction::makeDefend(stack);
  57. else
  58. return BattleAction::makeHeal(stack, woundHpToStack.rbegin()->second); //last element of the woundHpToStack is the most wounded stack
  59. }
  60. attemptCastingSpell();
  61. if(auto ret = getCbc()->battleIsFinished())
  62. {
  63. //spellcast may finish battle
  64. //send special preudo-action
  65. BattleAction cancel;
  66. cancel.actionType = Battle::CANCEL;
  67. return cancel;
  68. }
  69. if(auto action = considerFleeingOrSurrendering())
  70. return *action;
  71. PotentialTargets targets(stack);
  72. if(targets.possibleAttacks.size())
  73. {
  74. auto hlp = targets.bestAction();
  75. if(hlp.attack.shooting)
  76. return BattleAction::makeShotAttack(stack, hlp.enemy);
  77. else
  78. return BattleAction::makeMeleeAttack(stack, hlp.enemy, hlp.tile);
  79. }
  80. else
  81. {
  82. if(stack->waited())
  83. {
  84. //ThreatMap threatsToUs(stack); // These lines may be usefull but they are't used in the code.
  85. auto dists = getCbc()->battleGetDistances(stack);
  86. const EnemyInfo &ei= *range::min_element(targets.unreachableEnemies, std::bind(isCloser, _1, _2, std::ref(dists)));
  87. if(distToNearestNeighbour(ei.s->position, dists) < GameConstants::BFIELD_SIZE)
  88. {
  89. return goTowards(stack, ei.s->position);
  90. }
  91. }
  92. else
  93. {
  94. return BattleAction::makeWait(stack);
  95. }
  96. }
  97. }
  98. catch(std::exception &e)
  99. {
  100. logAi->error("Exception occurred in %s %s",__FUNCTION__, e.what());
  101. }
  102. return BattleAction::makeDefend(stack);
  103. }
  104. BattleAction CBattleAI::goTowards(const CStack * stack, BattleHex destination)
  105. {
  106. assert(destination.isValid());
  107. auto avHexes = cb->battleGetAvailableHexes(stack, false);
  108. auto reachability = cb->getReachability(stack);
  109. if(vstd::contains(avHexes, destination))
  110. return BattleAction::makeMove(stack, destination);
  111. auto destNeighbours = destination.neighbouringTiles();
  112. if(vstd::contains_if(destNeighbours, [&](BattleHex n) { return stack->coversPos(destination); }))
  113. {
  114. logAi->warn("Warning: already standing on neighbouring tile!");
  115. //We shouldn't even be here...
  116. return BattleAction::makeDefend(stack);
  117. }
  118. vstd::erase_if(destNeighbours, [&](BattleHex hex){ return !reachability.accessibility.accessible(hex, stack); });
  119. if(!avHexes.size() || !destNeighbours.size()) //we are blocked or dest is blocked
  120. {
  121. return BattleAction::makeDefend(stack);
  122. }
  123. if(stack->hasBonusOfType(Bonus::FLYING))
  124. {
  125. // Flying stack doesn't go hex by hex, so we can't backtrack using predecessors.
  126. // We just check all available hexes and pick the one closest to the target.
  127. auto distToDestNeighbour = [&](BattleHex hex) -> int
  128. {
  129. auto nearestNeighbourToHex = vstd::minElementByFun(destNeighbours, [&](BattleHex a)
  130. {return BattleHex::getDistance(a, hex);});
  131. return BattleHex::getDistance(*nearestNeighbourToHex, hex);
  132. };
  133. auto nearestAvailableHex = vstd::minElementByFun(avHexes, distToDestNeighbour);
  134. return BattleAction::makeMove(stack, *nearestAvailableHex);
  135. }
  136. else
  137. {
  138. BattleHex bestNeighbor = destination;
  139. if(distToNearestNeighbour(destination, reachability.distances, &bestNeighbor) > GameConstants::BFIELD_SIZE)
  140. {
  141. return BattleAction::makeDefend(stack);
  142. }
  143. BattleHex currentDest = bestNeighbor;
  144. while(1)
  145. {
  146. assert(currentDest.isValid());
  147. if(vstd::contains(avHexes, currentDest))
  148. return BattleAction::makeMove(stack, currentDest);
  149. currentDest = reachability.predecessors[currentDest];
  150. }
  151. }
  152. }
  153. BattleAction CBattleAI::useCatapult(const CStack * stack)
  154. {
  155. throw std::runtime_error("The method or operation is not implemented.");
  156. }
  157. enum SpellTypes
  158. {
  159. OFFENSIVE_SPELL, TIMED_EFFECT, OTHER
  160. };
  161. SpellTypes spellType(const CSpell *spell)
  162. {
  163. if (spell->isOffensiveSpell())
  164. return OFFENSIVE_SPELL;
  165. if (spell->hasEffects())
  166. return TIMED_EFFECT;
  167. return OTHER;
  168. }
  169. void CBattleAI::attemptCastingSpell()
  170. {
  171. auto hero = cb->battleGetMyHero();
  172. if(!hero)
  173. return;
  174. if(!cb->battleCanCastSpell())
  175. return;
  176. LOGL("Casting spells sounds like fun. Let's see...");
  177. //Get all spells we can cast
  178. std::vector<const CSpell*> possibleSpells;
  179. vstd::copy_if(VLC->spellh->objects, std::back_inserter(possibleSpells), [this] (const CSpell *s) -> bool
  180. {
  181. auto problem = getCbc()->battleCanCastThisSpell(s);
  182. return problem == ESpellCastProblem::OK;
  183. });
  184. LOGFL("I can cast %d spells.", possibleSpells.size());
  185. vstd::erase_if(possibleSpells, [](const CSpell *s)
  186. {return spellType(s) == OTHER; });
  187. LOGFL("I know about workings of %d of them.", possibleSpells.size());
  188. //Get possible spell-target pairs
  189. std::vector<PossibleSpellcast> possibleCasts;
  190. for(auto spell : possibleSpells)
  191. {
  192. for(auto hex : getTargetsToConsider(spell, hero))
  193. {
  194. PossibleSpellcast ps = {spell, hex, 0};
  195. possibleCasts.push_back(ps);
  196. }
  197. }
  198. LOGFL("Found %d spell-target combinations.", possibleCasts.size());
  199. if(possibleCasts.empty())
  200. return;
  201. std::map<const CStack*, int> valueOfStack;
  202. for(auto stack : cb->battleGetStacks())
  203. {
  204. PotentialTargets pt(stack);
  205. valueOfStack[stack] = pt.bestActionValue();
  206. }
  207. auto evaluateSpellcast = [&] (const PossibleSpellcast &ps) -> int
  208. {
  209. const int skillLevel = hero->getSpellSchoolLevel(ps.spell);
  210. const int spellPower = hero->getPrimSkillLevel(PrimarySkill::SPELL_POWER);
  211. switch(spellType(ps.spell))
  212. {
  213. case OFFENSIVE_SPELL:
  214. {
  215. int damageDealt = 0, damageReceived = 0;
  216. auto stacksSuffering = ps.spell->getAffectedStacks(cb.get(), ECastingMode::HERO_CASTING, hero, skillLevel, ps.dest);
  217. if(stacksSuffering.empty())
  218. return -1;
  219. for(auto stack : stacksSuffering)
  220. {
  221. const int dmg = ps.spell->calculateDamage(hero, stack, skillLevel, spellPower);
  222. if(stack->owner == playerID)
  223. damageReceived += dmg;
  224. else
  225. damageDealt += dmg;
  226. }
  227. const int damageDiff = damageDealt - damageReceived * 10;
  228. LOGFL("Casting %s on hex %d would deal { %d %d } damage points among %d stacks.",
  229. ps.spell->name % ps.dest % damageDealt % damageReceived % stacksSuffering.size());
  230. //TODO tactic effect too
  231. return damageDiff;
  232. }
  233. case TIMED_EFFECT:
  234. {
  235. auto stacksAffected = ps.spell->getAffectedStacks(cb.get(), ECastingMode::HERO_CASTING, hero, skillLevel, ps.dest);
  236. if(stacksAffected.empty())
  237. return -1;
  238. int totalGain = 0;
  239. for(const CStack * sta : stacksAffected)
  240. {
  241. StackWithBonuses swb;
  242. swb.stack = sta;
  243. Bonus pseudoBonus;
  244. pseudoBonus.sid = ps.spell->id;
  245. pseudoBonus.val = skillLevel;
  246. pseudoBonus.turnsRemain = 1; //TODO
  247. CStack::stackEffectToFeature(swb.bonusesToAdd, pseudoBonus);
  248. HypotheticChangesToBattleState state;
  249. state.bonusesOfStacks[swb.stack] = &swb;
  250. PotentialTargets pt(swb.stack, state);
  251. auto newValue = pt.bestActionValue();
  252. auto oldValue = valueOfStack[swb.stack];
  253. auto gain = newValue - oldValue;
  254. if(swb.stack->owner != playerID) //enemy
  255. gain = -gain;
  256. LOGFL("Casting %s on %s would improve the stack by %d points (from %d to %d)",
  257. ps.spell->name % sta->nodeName() % (gain) % (oldValue) % (newValue));
  258. totalGain += gain;
  259. }
  260. LOGFL("Total gain of cast %s at hex %d is %d", ps.spell->name % (ps.dest.hex) % (totalGain));
  261. return totalGain;
  262. }
  263. default:
  264. assert(0);
  265. return 0;
  266. }
  267. };
  268. for(PossibleSpellcast & psc : possibleCasts)
  269. psc.value = evaluateSpellcast(psc);
  270. auto pscValue = [] (const PossibleSpellcast &ps) -> int
  271. {
  272. return ps.value;
  273. };
  274. auto castToPerform = *vstd::maxElementByFun(possibleCasts, pscValue);
  275. LOGFL("Best spell is %s. Will cast.", castToPerform.spell->name);
  276. BattleAction spellcast;
  277. spellcast.actionType = Battle::HERO_SPELL;
  278. spellcast.additionalInfo = castToPerform.spell->id;
  279. spellcast.destinationTile = castToPerform.dest;
  280. spellcast.side = side;
  281. spellcast.stackNumber = (!side) ? -1 : -2;
  282. cb->battleMakeAction(&spellcast);
  283. }
  284. std::vector<BattleHex> CBattleAI::getTargetsToConsider(const CSpell * spell, const ISpellCaster * caster) const
  285. {
  286. const CSpell::TargetInfo targetInfo(spell, caster->getSpellSchoolLevel(spell));
  287. std::vector<BattleHex> ret;
  288. if(targetInfo.massive || targetInfo.type == CSpell::NO_TARGET)
  289. {
  290. ret.push_back(BattleHex());
  291. }
  292. else
  293. {
  294. switch(targetInfo.type)
  295. {
  296. case CSpell::CREATURE:
  297. {
  298. for(const CStack * stack : getCbc()->battleAliveStacks())
  299. {
  300. bool immune = ESpellCastProblem::OK != spell->isImmuneByStack(caster, stack);
  301. bool casterStack = stack->owner == caster->getOwner();
  302. if(!immune)
  303. switch (spell->positiveness)
  304. {
  305. case CSpell::POSITIVE:
  306. if(casterStack || targetInfo.smart)
  307. ret.push_back(stack->position);
  308. break;
  309. case CSpell::NEUTRAL:
  310. ret.push_back(stack->position);
  311. break;
  312. case CSpell::NEGATIVE:
  313. if(!casterStack || targetInfo.smart)
  314. ret.push_back(stack->position);
  315. break;
  316. }
  317. }
  318. }
  319. break;
  320. case CSpell::LOCATION:
  321. {
  322. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  323. if(BattleHex(i).isAvailable())
  324. ret.push_back(i);
  325. }
  326. break;
  327. default:
  328. break;
  329. }
  330. }
  331. return ret;
  332. }
  333. int CBattleAI::distToNearestNeighbour(BattleHex hex, const ReachabilityInfo::TDistances &dists, BattleHex *chosenHex)
  334. {
  335. int ret = 1000000;
  336. for(BattleHex n : hex.neighbouringTiles())
  337. {
  338. if(dists[n] >= 0 && dists[n] < ret)
  339. {
  340. ret = dists[n];
  341. if(chosenHex)
  342. *chosenHex = n;
  343. }
  344. }
  345. return ret;
  346. }
  347. void CBattleAI::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool Side)
  348. {
  349. print("battleStart called");
  350. side = Side;
  351. }
  352. bool CBattleAI::isCloser(const EnemyInfo &ei1, const EnemyInfo &ei2, const ReachabilityInfo::TDistances &dists)
  353. {
  354. return distToNearestNeighbour(ei1.s->position, dists) < distToNearestNeighbour(ei2.s->position, dists);
  355. }
  356. void CBattleAI::print(const std::string &text) const
  357. {
  358. logAi->trace("CBattleAI [%p]: %s", this, text);
  359. }
  360. boost::optional<BattleAction> CBattleAI::considerFleeingOrSurrendering()
  361. {
  362. if(cb->battleCanSurrender(playerID))
  363. {
  364. }
  365. if(cb->battleCanFlee())
  366. {
  367. }
  368. return boost::none;
  369. }