BattleAI.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  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()
  18. : side(-1), wasWaitingForRealize(false), wasUnlockingGs(false)
  19. {
  20. }
  21. CBattleAI::~CBattleAI()
  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->getFirstHPleft())
  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(boost::thread_interrupted &)
  99. {
  100. throw;
  101. }
  102. catch(std::exception &e)
  103. {
  104. logAi->error("Exception occurred in %s %s",__FUNCTION__, e.what());
  105. }
  106. return BattleAction::makeDefend(stack);
  107. }
  108. BattleAction CBattleAI::goTowards(const CStack * stack, BattleHex destination)
  109. {
  110. assert(destination.isValid());
  111. auto avHexes = cb->battleGetAvailableHexes(stack, false);
  112. auto reachability = cb->getReachability(stack);
  113. if(vstd::contains(avHexes, destination))
  114. return BattleAction::makeMove(stack, destination);
  115. auto destNeighbours = destination.neighbouringTiles();
  116. if(vstd::contains_if(destNeighbours, [&](BattleHex n) { return stack->coversPos(destination); }))
  117. {
  118. logAi->warn("Warning: already standing on neighbouring tile!");
  119. //We shouldn't even be here...
  120. return BattleAction::makeDefend(stack);
  121. }
  122. vstd::erase_if(destNeighbours, [&](BattleHex hex){ return !reachability.accessibility.accessible(hex, stack); });
  123. if(!avHexes.size() || !destNeighbours.size()) //we are blocked or dest is blocked
  124. {
  125. return BattleAction::makeDefend(stack);
  126. }
  127. if(stack->hasBonusOfType(Bonus::FLYING))
  128. {
  129. // Flying stack doesn't go hex by hex, so we can't backtrack using predecessors.
  130. // We just check all available hexes and pick the one closest to the target.
  131. auto distToDestNeighbour = [&](BattleHex hex) -> int
  132. {
  133. auto nearestNeighbourToHex = vstd::minElementByFun(destNeighbours, [&](BattleHex a)
  134. {return BattleHex::getDistance(a, hex);});
  135. return BattleHex::getDistance(*nearestNeighbourToHex, hex);
  136. };
  137. auto nearestAvailableHex = vstd::minElementByFun(avHexes, distToDestNeighbour);
  138. return BattleAction::makeMove(stack, *nearestAvailableHex);
  139. }
  140. else
  141. {
  142. BattleHex bestNeighbor = destination;
  143. if(distToNearestNeighbour(destination, reachability.distances, &bestNeighbor) > GameConstants::BFIELD_SIZE)
  144. {
  145. return BattleAction::makeDefend(stack);
  146. }
  147. BattleHex currentDest = bestNeighbor;
  148. while(1)
  149. {
  150. assert(currentDest.isValid());
  151. if(vstd::contains(avHexes, currentDest))
  152. return BattleAction::makeMove(stack, currentDest);
  153. currentDest = reachability.predecessors[currentDest];
  154. }
  155. }
  156. }
  157. BattleAction CBattleAI::useCatapult(const CStack * stack)
  158. {
  159. throw std::runtime_error("The method or operation is not implemented.");
  160. }
  161. enum SpellTypes
  162. {
  163. OFFENSIVE_SPELL, TIMED_EFFECT, OTHER
  164. };
  165. SpellTypes spellType(const CSpell *spell)
  166. {
  167. if (spell->isOffensiveSpell())
  168. return OFFENSIVE_SPELL;
  169. if (spell->hasEffects())
  170. return TIMED_EFFECT;
  171. return OTHER;
  172. }
  173. void CBattleAI::attemptCastingSpell()
  174. {
  175. auto hero = cb->battleGetMyHero();
  176. if(!hero)
  177. return;
  178. if(cb->battleCanCastSpell(hero, ECastingMode::HERO_CASTING) != ESpellCastProblem::OK)
  179. return;
  180. LOGL("Casting spells sounds like fun. Let's see...");
  181. //Get all spells we can cast
  182. std::vector<const CSpell*> possibleSpells;
  183. vstd::copy_if(VLC->spellh->objects, std::back_inserter(possibleSpells), [this, hero] (const CSpell *s) -> bool
  184. {
  185. return s->canBeCast(getCbc().get(), ECastingMode::HERO_CASTING, hero) == ESpellCastProblem::OK;
  186. });
  187. LOGFL("I can cast %d spells.", possibleSpells.size());
  188. vstd::erase_if(possibleSpells, [](const CSpell *s)
  189. {return spellType(s) == OTHER; });
  190. LOGFL("I know about workings of %d of them.", possibleSpells.size());
  191. //Get possible spell-target pairs
  192. std::vector<PossibleSpellcast> possibleCasts;
  193. for(auto spell : possibleSpells)
  194. {
  195. for(auto hex : getTargetsToConsider(spell, hero))
  196. {
  197. PossibleSpellcast ps = {spell, hex, 0};
  198. possibleCasts.push_back(ps);
  199. }
  200. }
  201. LOGFL("Found %d spell-target combinations.", possibleCasts.size());
  202. if(possibleCasts.empty())
  203. return;
  204. std::map<const CStack*, int> valueOfStack;
  205. for(auto stack : cb->battleGetStacks())
  206. {
  207. PotentialTargets pt(stack);
  208. valueOfStack[stack] = pt.bestActionValue();
  209. }
  210. auto evaluateSpellcast = [&] (const PossibleSpellcast &ps) -> int
  211. {
  212. const int skillLevel = hero->getSpellSchoolLevel(ps.spell);
  213. const int spellPower = hero->getPrimSkillLevel(PrimarySkill::SPELL_POWER);
  214. switch(spellType(ps.spell))
  215. {
  216. case OFFENSIVE_SPELL:
  217. {
  218. int damageDealt = 0, damageReceived = 0;
  219. auto stacksSuffering = ps.spell->getAffectedStacks(cb.get(), ECastingMode::HERO_CASTING, hero, skillLevel, ps.dest);
  220. if(stacksSuffering.empty())
  221. return -1;
  222. for(auto stack : stacksSuffering)
  223. {
  224. const int dmg = ps.spell->calculateDamage(hero, stack, skillLevel, spellPower);
  225. if(stack->owner == playerID)
  226. damageReceived += dmg;
  227. else
  228. damageDealt += dmg;
  229. }
  230. const int damageDiff = damageDealt - damageReceived * 10;
  231. LOGFL("Casting %s on hex %d would deal { %d %d } damage points among %d stacks.",
  232. ps.spell->name % ps.dest % damageDealt % damageReceived % stacksSuffering.size());
  233. //TODO tactic effect too
  234. return damageDiff;
  235. }
  236. case TIMED_EFFECT:
  237. {
  238. auto stacksAffected = ps.spell->getAffectedStacks(cb.get(), ECastingMode::HERO_CASTING, hero, skillLevel, ps.dest);
  239. if(stacksAffected.empty())
  240. return -1;
  241. int totalGain = 0;
  242. for(const CStack * sta : stacksAffected)
  243. {
  244. StackWithBonuses swb;
  245. swb.stack = sta;
  246. //todo: handle effect actualization in HypotheticChangesToBattleState
  247. ps.spell->getEffects(swb.bonusesToAdd, skillLevel, false, hero->getEnchantPower(ps.spell));
  248. ps.spell->getEffects(swb.bonusesToAdd, skillLevel, true, hero->getEnchantPower(ps.spell));
  249. HypotheticChangesToBattleState state;
  250. state.bonusesOfStacks[swb.stack] = &swb;
  251. PotentialTargets pt(swb.stack, state);
  252. auto newValue = pt.bestActionValue();
  253. auto oldValue = valueOfStack[swb.stack];
  254. auto gain = newValue - oldValue;
  255. if(swb.stack->owner != playerID) //enemy
  256. gain = -gain;
  257. LOGFL("Casting %s on %s would improve the stack by %d points (from %d to %d)",
  258. ps.spell->name % sta->nodeName() % (gain) % (oldValue) % (newValue));
  259. totalGain += gain;
  260. }
  261. LOGFL("Total gain of cast %s at hex %d is %d", ps.spell->name % (ps.dest.hex) % (totalGain));
  262. return totalGain;
  263. }
  264. default:
  265. assert(0);
  266. return 0;
  267. }
  268. };
  269. for(PossibleSpellcast & psc : possibleCasts)
  270. psc.value = evaluateSpellcast(psc);
  271. auto pscValue = [] (const PossibleSpellcast &ps) -> int
  272. {
  273. return ps.value;
  274. };
  275. auto castToPerform = *vstd::maxElementByFun(possibleCasts, pscValue);
  276. LOGFL("Best spell is %s. Will cast.", castToPerform.spell->name);
  277. BattleAction spellcast;
  278. spellcast.actionType = Battle::HERO_SPELL;
  279. spellcast.additionalInfo = castToPerform.spell->id;
  280. spellcast.destinationTile = castToPerform.dest;
  281. spellcast.side = side;
  282. spellcast.stackNumber = (!side) ? -1 : -2;
  283. cb->battleMakeAction(&spellcast);
  284. }
  285. std::vector<BattleHex> CBattleAI::getTargetsToConsider(const CSpell * spell, const ISpellCaster * caster) const
  286. {
  287. const CSpell::TargetInfo targetInfo(spell, caster->getSpellSchoolLevel(spell));
  288. std::vector<BattleHex> ret;
  289. if(targetInfo.massive || targetInfo.type == CSpell::NO_TARGET)
  290. {
  291. ret.push_back(BattleHex());
  292. }
  293. else
  294. {
  295. switch(targetInfo.type)
  296. {
  297. case CSpell::CREATURE:
  298. {
  299. for(const CStack * stack : getCbc()->battleAliveStacks())
  300. {
  301. bool immune = ESpellCastProblem::OK != spell->isImmuneByStack(caster, stack);
  302. bool casterStack = stack->owner == caster->getOwner();
  303. if(!immune)
  304. switch (spell->positiveness)
  305. {
  306. case CSpell::POSITIVE:
  307. if(casterStack || targetInfo.smart)
  308. ret.push_back(stack->position);
  309. break;
  310. case CSpell::NEUTRAL:
  311. ret.push_back(stack->position);
  312. break;
  313. case CSpell::NEGATIVE:
  314. if(!casterStack || targetInfo.smart)
  315. ret.push_back(stack->position);
  316. break;
  317. }
  318. }
  319. }
  320. break;
  321. case CSpell::LOCATION:
  322. {
  323. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  324. if(BattleHex(i).isAvailable())
  325. ret.push_back(i);
  326. }
  327. break;
  328. default:
  329. break;
  330. }
  331. }
  332. return ret;
  333. }
  334. int CBattleAI::distToNearestNeighbour(BattleHex hex, const ReachabilityInfo::TDistances &dists, BattleHex *chosenHex)
  335. {
  336. int ret = 1000000;
  337. for(BattleHex n : hex.neighbouringTiles())
  338. {
  339. if(dists[n] >= 0 && dists[n] < ret)
  340. {
  341. ret = dists[n];
  342. if(chosenHex)
  343. *chosenHex = n;
  344. }
  345. }
  346. return ret;
  347. }
  348. void CBattleAI::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool Side)
  349. {
  350. print("battleStart called");
  351. side = Side;
  352. }
  353. bool CBattleAI::isCloser(const EnemyInfo &ei1, const EnemyInfo &ei2, const ReachabilityInfo::TDistances &dists)
  354. {
  355. return distToNearestNeighbour(ei1.s->position, dists) < distToNearestNeighbour(ei2.s->position, dists);
  356. }
  357. void CBattleAI::print(const std::string &text) const
  358. {
  359. logAi->trace("CBattleAI [%p]: %s", this, text);
  360. }
  361. boost::optional<BattleAction> CBattleAI::considerFleeingOrSurrendering()
  362. {
  363. if(cb->battleCanSurrender(playerID))
  364. {
  365. }
  366. if(cb->battleCanFlee())
  367. {
  368. }
  369. return boost::none;
  370. }