2
0

BattleAI.cpp 12 KB

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