BattleAI.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  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 <vstd/RNG.h>
  13. #include "StackWithBonuses.h"
  14. #include "EnemyInfo.h"
  15. #include "../../lib/CStopWatch.h"
  16. #include "../../lib/CThreadHelper.h"
  17. #include "../../lib/spells/CSpellHandler.h"
  18. #include "../../lib/spells/ISpellMechanics.h"
  19. #include "../../lib/CStack.h" // TODO: remove
  20. // Eventually only IBattleInfoCallback and battle::Unit should be used,
  21. // CUnitState should be private and CStack should be removed completely
  22. #define LOGL(text) print(text)
  23. #define LOGFL(text, formattingEl) print(boost::str(boost::format(text) % formattingEl))
  24. class RNGStub : public vstd::RNG
  25. {
  26. public:
  27. vstd::TRandI64 getInt64Range(int64_t lower, int64_t upper) override
  28. {
  29. return [=]()->int64_t
  30. {
  31. return (lower + upper)/2;
  32. };
  33. }
  34. vstd::TRand getDoubleRange(double lower, double upper) override
  35. {
  36. return [=]()->double
  37. {
  38. return (lower + upper)/2;
  39. };
  40. }
  41. };
  42. enum class SpellTypes
  43. {
  44. ADVENTURE, BATTLE, OTHER
  45. };
  46. SpellTypes spellType(const CSpell * spell)
  47. {
  48. if(!spell->isCombatSpell() || spell->isCreatureAbility())
  49. return SpellTypes::OTHER;
  50. if(spell->isOffensiveSpell() || spell->hasEffects() || spell->hasBattleEffects())
  51. return SpellTypes::BATTLE;
  52. return SpellTypes::OTHER;
  53. }
  54. CBattleAI::CBattleAI()
  55. : side(-1), wasWaitingForRealize(false), wasUnlockingGs(false)
  56. {
  57. }
  58. CBattleAI::~CBattleAI()
  59. {
  60. if(cb)
  61. {
  62. //Restore previous state of CB - it may be shared with the main AI (like VCAI)
  63. cb->waitTillRealize = wasWaitingForRealize;
  64. cb->unlockGsWhenWaiting = wasUnlockingGs;
  65. }
  66. }
  67. void CBattleAI::init(std::shared_ptr<CBattleCallback> CB)
  68. {
  69. setCbc(CB);
  70. cb = CB;
  71. playerID = *CB->getPlayerID(); //TODO should be sth in callback
  72. wasWaitingForRealize = cb->waitTillRealize;
  73. wasUnlockingGs = CB->unlockGsWhenWaiting;
  74. CB->waitTillRealize = true;
  75. CB->unlockGsWhenWaiting = false;
  76. }
  77. BattleAction CBattleAI::activeStack( const CStack * stack )
  78. {
  79. LOG_TRACE_PARAMS(logAi, "stack: %s", stack->nodeName()) ;
  80. setCbc(cb); //TODO: make solid sure that AIs always use their callbacks (need to take care of event handlers too)
  81. try
  82. {
  83. if(stack->type->idNumber == CreatureID::CATAPULT)
  84. return useCatapult(stack);
  85. if(stack->hasBonusOfType(Bonus::SIEGE_WEAPON) && stack->hasBonusOfType(Bonus::HEALER))
  86. {
  87. auto healingTargets = cb->battleGetStacks(CBattleInfoEssentials::ONLY_MINE);
  88. std::map<int, const CStack*> woundHpToStack;
  89. for(auto stack : healingTargets)
  90. if(auto woundHp = stack->MaxHealth() - stack->getFirstHPleft())
  91. woundHpToStack[woundHp] = stack;
  92. if(woundHpToStack.empty())
  93. return BattleAction::makeDefend(stack);
  94. else
  95. return BattleAction::makeHeal(stack, woundHpToStack.rbegin()->second); //last element of the woundHpToStack is the most wounded stack
  96. }
  97. attemptCastingSpell();
  98. if(auto ret = getCbc()->battleIsFinished())
  99. {
  100. //spellcast may finish battle
  101. //send special preudo-action
  102. BattleAction cancel;
  103. cancel.actionType = EActionType::CANCEL;
  104. return cancel;
  105. }
  106. if(auto action = considerFleeingOrSurrendering())
  107. return *action;
  108. //best action is from effective owner point if view, we are effective owner as we received "activeStack"
  109. //evaluate casting spell for spellcasting stack
  110. boost::optional<PossibleSpellcast> bestSpellcast(boost::none);
  111. //TODO: faerie dragon type spell should be selected by server
  112. SpellID creatureSpellToCast = cb->battleGetRandomStackSpell(CRandomGenerator::getDefault(), stack, CBattleInfoCallback::RANDOM_AIMED);
  113. if(stack->hasBonusOfType(Bonus::SPELLCASTER) && stack->canCast() && creatureSpellToCast != SpellID::NONE)
  114. {
  115. const CSpell * spell = creatureSpellToCast.toSpell();
  116. if(spell->canBeCast(getCbc().get(), spells::Mode::CREATURE_ACTIVE, stack))
  117. {
  118. std::vector<PossibleSpellcast> possibleCasts;
  119. spells::BattleCast temp(getCbc().get(), stack, spells::Mode::CREATURE_ACTIVE, spell);
  120. for(auto & target : temp.findPotentialTargets())
  121. {
  122. PossibleSpellcast ps;
  123. ps.dest = target;
  124. ps.spell = spell;
  125. evaluateCreatureSpellcast(stack, ps);
  126. possibleCasts.push_back(ps);
  127. }
  128. std::sort(possibleCasts.begin(), possibleCasts.end(), [&](const PossibleSpellcast & lhs, const PossibleSpellcast & rhs) { return lhs.value > rhs.value; });
  129. if(!possibleCasts.empty() && possibleCasts.front().value > 0)
  130. {
  131. bestSpellcast = boost::optional<PossibleSpellcast>(possibleCasts.front());
  132. }
  133. }
  134. }
  135. HypotheticBattle hb(getCbc());
  136. PotentialTargets targets(stack, &hb);
  137. if(!targets.possibleAttacks.empty())
  138. {
  139. AttackPossibility bestAttack = targets.bestAction();
  140. //TODO: consider more complex spellcast evaluation, f.e. because "re-retaliation" during enemy move in same turn for melee attack etc.
  141. if(bestSpellcast.is_initialized() && bestSpellcast->value > bestAttack.damageDiff())
  142. return BattleAction::makeCreatureSpellcast(stack, bestSpellcast->dest, bestSpellcast->spell->id);
  143. else if(bestAttack.attack.shooting)
  144. return BattleAction::makeShotAttack(stack, bestAttack.attack.defender);
  145. else
  146. {
  147. auto &target = bestAttack;
  148. logAi->debug("BattleAI: %s -> %s %d from, %d curpos %d dist %d speed %d: %lld %lld %lld",
  149. target.attackerState->unitType()->identifier,
  150. target.affectedUnits[0]->unitType()->identifier,
  151. (int)target.affectedUnits.size(), (int)target.from, (int)bestAttack.attack.attacker->getPosition().hex,
  152. bestAttack.attack.chargedFields, bestAttack.attack.attacker->Speed(0, true),
  153. target.damageDealt, target.damageReceived, target.attackValue()
  154. );
  155. return BattleAction::makeMeleeAttack(stack, bestAttack.attack.defender->getPosition(), bestAttack.from);
  156. }
  157. }
  158. else if(bestSpellcast.is_initialized())
  159. {
  160. return BattleAction::makeCreatureSpellcast(stack, bestSpellcast->dest, bestSpellcast->spell->id);
  161. }
  162. else
  163. {
  164. if(stack->waited())
  165. {
  166. //ThreatMap threatsToUs(stack); // These lines may be usefull but they are't used in the code.
  167. auto dists = getCbc()->battleGetDistances(stack, stack->getPosition());
  168. if(!targets.unreachableEnemies.empty())
  169. {
  170. const EnemyInfo &ei= *range::min_element(targets.unreachableEnemies, std::bind(isCloser, _1, _2, std::ref(dists)));
  171. if(distToNearestNeighbour(ei.s->getPosition(), dists) < GameConstants::BFIELD_SIZE)
  172. {
  173. return goTowards(stack, ei.s->getPosition());
  174. }
  175. }
  176. }
  177. else
  178. {
  179. return BattleAction::makeWait(stack);
  180. }
  181. }
  182. }
  183. catch(boost::thread_interrupted &)
  184. {
  185. throw;
  186. }
  187. catch(std::exception &e)
  188. {
  189. logAi->error("Exception occurred in %s %s",__FUNCTION__, e.what());
  190. }
  191. return BattleAction::makeDefend(stack);
  192. }
  193. BattleAction CBattleAI::goTowards(const CStack * stack, BattleHex destination)
  194. {
  195. if(!destination.isValid())
  196. {
  197. logAi->error("CBattleAI::goTowards: invalid destination");
  198. return BattleAction::makeDefend(stack);
  199. }
  200. auto reachability = cb->getReachability(stack);
  201. auto avHexes = cb->battleGetAvailableHexes(reachability, stack);
  202. if(vstd::contains(avHexes, destination))
  203. return BattleAction::makeMove(stack, destination);
  204. auto destNeighbours = destination.neighbouringTiles();
  205. if(vstd::contains_if(destNeighbours, [&](BattleHex n) { return stack->coversPos(destination); }))
  206. {
  207. logAi->warn("Warning: already standing on neighbouring tile!");
  208. //We shouldn't even be here...
  209. return BattleAction::makeDefend(stack);
  210. }
  211. vstd::erase_if(destNeighbours, [&](BattleHex hex){ return !reachability.accessibility.accessible(hex, stack); });
  212. if(!avHexes.size() || !destNeighbours.size()) //we are blocked or dest is blocked
  213. {
  214. return BattleAction::makeDefend(stack);
  215. }
  216. if(stack->hasBonusOfType(Bonus::FLYING))
  217. {
  218. // Flying stack doesn't go hex by hex, so we can't backtrack using predecessors.
  219. // We just check all available hexes and pick the one closest to the target.
  220. auto distToDestNeighbour = [&](BattleHex hex) -> int
  221. {
  222. auto nearestNeighbourToHex = vstd::minElementByFun(destNeighbours, [&](BattleHex a)
  223. {return BattleHex::getDistance(a, hex);});
  224. return BattleHex::getDistance(*nearestNeighbourToHex, hex);
  225. };
  226. auto nearestAvailableHex = vstd::minElementByFun(avHexes, distToDestNeighbour);
  227. return BattleAction::makeMove(stack, *nearestAvailableHex);
  228. }
  229. else
  230. {
  231. BattleHex bestNeighbor = destination;
  232. if(distToNearestNeighbour(destination, reachability.distances, &bestNeighbor) > GameConstants::BFIELD_SIZE)
  233. {
  234. return BattleAction::makeDefend(stack);
  235. }
  236. BattleHex currentDest = bestNeighbor;
  237. while(1)
  238. {
  239. if(!currentDest.isValid())
  240. {
  241. logAi->error("CBattleAI::goTowards: internal error");
  242. return BattleAction::makeDefend(stack);
  243. }
  244. if(vstd::contains(avHexes, currentDest))
  245. return BattleAction::makeMove(stack, currentDest);
  246. currentDest = reachability.predecessors[currentDest];
  247. }
  248. }
  249. }
  250. BattleAction CBattleAI::useCatapult(const CStack * stack)
  251. {
  252. throw std::runtime_error("CBattleAI::useCatapult is not implemented.");
  253. }
  254. void CBattleAI::attemptCastingSpell()
  255. {
  256. auto hero = cb->battleGetMyHero();
  257. if(!hero)
  258. return;
  259. if(cb->battleCanCastSpell(hero, spells::Mode::HERO) != ESpellCastProblem::OK)
  260. return;
  261. LOGL("Casting spells sounds like fun. Let's see...");
  262. //Get all spells we can cast
  263. std::vector<const CSpell*> possibleSpells;
  264. vstd::copy_if(VLC->spellh->objects, std::back_inserter(possibleSpells), [hero](const CSpell *s) -> bool
  265. {
  266. return s->canBeCast(getCbc().get(), spells::Mode::HERO, hero);
  267. });
  268. LOGFL("I can cast %d spells.", possibleSpells.size());
  269. vstd::erase_if(possibleSpells, [](const CSpell *s)
  270. {
  271. return spellType(s) != SpellTypes::BATTLE;
  272. });
  273. LOGFL("I know how %d of them works.", possibleSpells.size());
  274. //Get possible spell-target pairs
  275. std::vector<PossibleSpellcast> possibleCasts;
  276. for(auto spell : possibleSpells)
  277. {
  278. spells::BattleCast temp(getCbc().get(), hero, spells::Mode::HERO, spell);
  279. for(auto & target : temp.findPotentialTargets())
  280. {
  281. PossibleSpellcast ps;
  282. ps.dest = target;
  283. ps.spell = spell;
  284. possibleCasts.push_back(ps);
  285. }
  286. }
  287. LOGFL("Found %d spell-target combinations.", possibleCasts.size());
  288. if(possibleCasts.empty())
  289. return;
  290. using ValueMap = PossibleSpellcast::ValueMap;
  291. auto evaluateQueue = [&](ValueMap & values, const std::vector<battle::Units> & queue, HypotheticBattle * state, size_t minTurnSpan, bool * enemyHadTurnOut) -> bool
  292. {
  293. bool firstRound = true;
  294. bool enemyHadTurn = false;
  295. size_t ourTurnSpan = 0;
  296. bool stop = false;
  297. for(auto & round : queue)
  298. {
  299. if(!firstRound)
  300. state->nextRound(0);//todo: set actual value?
  301. for(auto unit : round)
  302. {
  303. if(!vstd::contains(values, unit->unitId()))
  304. values[unit->unitId()] = 0;
  305. if(!unit->alive())
  306. continue;
  307. if(state->battleGetOwner(unit) != playerID)
  308. {
  309. enemyHadTurn = true;
  310. if(!firstRound || state->battleCastSpells(unit->unitSide()) == 0)
  311. {
  312. //enemy could counter our spell at this point
  313. //anyway, we do not know what enemy will do
  314. //just stop evaluation
  315. stop = true;
  316. break;
  317. }
  318. }
  319. else if(!enemyHadTurn)
  320. {
  321. ourTurnSpan++;
  322. }
  323. state->nextTurn(unit->unitId());
  324. PotentialTargets pt(unit, state);
  325. if(!pt.possibleAttacks.empty())
  326. {
  327. AttackPossibility ap = pt.bestAction();
  328. auto swb = state->getForUpdate(unit->unitId());
  329. *swb = *ap.attackerState;
  330. if(ap.damageDealt > 0)
  331. swb->removeUnitBonus(Bonus::UntilAttack);
  332. if(ap.damageReceived > 0)
  333. swb->removeUnitBonus(Bonus::UntilBeingAttacked);
  334. for(auto affected : ap.affectedUnits)
  335. {
  336. swb = state->getForUpdate(affected->unitId());
  337. *swb = *affected;
  338. if(ap.damageDealt > 0)
  339. swb->removeUnitBonus(Bonus::UntilBeingAttacked);
  340. if(ap.damageReceived > 0 && ap.attack.defender->unitId() == affected->unitId())
  341. swb->removeUnitBonus(Bonus::UntilAttack);
  342. }
  343. }
  344. auto bav = pt.bestActionValue();
  345. //best action is from effective owner`s point if view, we need to convert to our point if view
  346. if(state->battleGetOwner(unit) != playerID)
  347. bav = -bav;
  348. values[unit->unitId()] += bav;
  349. }
  350. firstRound = false;
  351. if(stop)
  352. break;
  353. }
  354. if(enemyHadTurnOut)
  355. *enemyHadTurnOut = enemyHadTurn;
  356. return ourTurnSpan >= minTurnSpan;
  357. };
  358. RNGStub rngStub;
  359. ValueMap valueOfStack;
  360. ValueMap healthOfStack;
  361. TStacks all = cb->battleGetAllStacks(false);
  362. size_t ourRemainingTurns = 0;
  363. for(auto unit : all)
  364. {
  365. healthOfStack[unit->unitId()] = unit->getAvailableHealth();
  366. valueOfStack[unit->unitId()] = 0;
  367. if(cb->battleGetOwner(unit) == playerID && unit->canMove() && !unit->moved())
  368. ourRemainingTurns++;
  369. }
  370. LOGFL("I have %d turns left in this round", ourRemainingTurns);
  371. const bool castNow = ourRemainingTurns <= 1;
  372. if(castNow)
  373. print("I should try to cast a spell now");
  374. else
  375. print("I could wait better moment to cast a spell");
  376. auto amount = all.size();
  377. std::vector<battle::Units> turnOrder;
  378. cb->battleGetTurnOrder(turnOrder, amount, 2); //no more than 1 turn after current, each unit at least once
  379. {
  380. bool enemyHadTurn = false;
  381. HypotheticBattle state(cb);
  382. evaluateQueue(valueOfStack, turnOrder, &state, 0, &enemyHadTurn);
  383. if(!enemyHadTurn)
  384. {
  385. auto battleIsFinishedOpt = state.battleIsFinished();
  386. if(battleIsFinishedOpt)
  387. {
  388. print("No need to cast a spell. Battle will finish soon.");
  389. return;
  390. }
  391. }
  392. }
  393. auto evaluateSpellcast = [&] (PossibleSpellcast * ps)
  394. {
  395. HypotheticBattle state(cb);
  396. spells::BattleCast cast(&state, hero, spells::Mode::HERO, ps->spell);
  397. cast.target = ps->dest;
  398. cast.cast(&state, rngStub);
  399. ValueMap newHealthOfStack;
  400. ValueMap newValueOfStack;
  401. size_t ourUnits = 0;
  402. for(auto unit : all)
  403. {
  404. auto unitId = unit->unitId();
  405. auto localUnit = state.battleGetUnitByID(unitId);
  406. newHealthOfStack[unitId] = localUnit->getAvailableHealth();
  407. newValueOfStack[unitId] = 0;
  408. if(state.battleGetOwner(localUnit) == playerID && localUnit->alive() && localUnit->willMove())
  409. ourUnits++;
  410. }
  411. size_t minTurnSpan = ourUnits/3; //todo: tweak this
  412. std::vector<battle::Units> newTurnOrder;
  413. state.battleGetTurnOrder(newTurnOrder, amount, 2);
  414. const bool turnSpanOK = evaluateQueue(newValueOfStack, newTurnOrder, &state, minTurnSpan, nullptr);
  415. if(turnSpanOK || castNow)
  416. {
  417. int64_t totalGain = 0;
  418. for(auto unit : all)
  419. {
  420. auto unitId = unit->unitId();
  421. auto localUnit = state.battleGetUnitByID(unitId);
  422. auto newValue = getValOr(newValueOfStack, unitId, 0);
  423. auto oldValue = getValOr(valueOfStack, unitId, 0);
  424. auto healthDiff = newHealthOfStack[unitId] - healthOfStack[unitId];
  425. if(localUnit->unitOwner() != playerID)
  426. healthDiff = -healthDiff;
  427. if(healthDiff < 0)
  428. {
  429. ps->value = -1;
  430. return; //do not damage own units at all
  431. }
  432. totalGain += (newValue - oldValue + healthDiff);
  433. }
  434. ps->value = totalGain;
  435. }
  436. else
  437. {
  438. ps->value = -1;
  439. }
  440. };
  441. std::vector<std::function<void()>> tasks;
  442. for(PossibleSpellcast & psc : possibleCasts)
  443. tasks.push_back(std::bind(evaluateSpellcast, &psc));
  444. uint32_t threadCount = boost::thread::hardware_concurrency();
  445. if(threadCount == 0)
  446. {
  447. logGlobal->warn("No information of CPU cores available");
  448. threadCount = 1;
  449. }
  450. CStopWatch timer;
  451. CThreadHelper threadHelper(&tasks, threadCount);
  452. threadHelper.run();
  453. LOGFL("Evaluation took %d ms", timer.getDiff());
  454. auto pscValue = [](const PossibleSpellcast &ps) -> int64_t
  455. {
  456. return ps.value;
  457. };
  458. auto castToPerform = *vstd::maxElementByFun(possibleCasts, pscValue);
  459. if(castToPerform.value > 0)
  460. {
  461. LOGFL("Best spell is %s (value %d). Will cast.", castToPerform.spell->name % castToPerform.value);
  462. BattleAction spellcast;
  463. spellcast.actionType = EActionType::HERO_SPELL;
  464. spellcast.actionSubtype = castToPerform.spell->id;
  465. spellcast.setTarget(castToPerform.dest);
  466. spellcast.side = side;
  467. spellcast.stackNumber = (!side) ? -1 : -2;
  468. cb->battleMakeAction(&spellcast);
  469. }
  470. else
  471. {
  472. LOGFL("Best spell is %s. But it is actually useless (value %d).", castToPerform.spell->name % castToPerform.value);
  473. }
  474. }
  475. //Below method works only for offensive spells
  476. void CBattleAI::evaluateCreatureSpellcast(const CStack * stack, PossibleSpellcast & ps)
  477. {
  478. using ValueMap = PossibleSpellcast::ValueMap;
  479. RNGStub rngStub;
  480. HypotheticBattle state(getCbc());
  481. TStacks all = getCbc()->battleGetAllStacks(false);
  482. ValueMap healthOfStack;
  483. ValueMap newHealthOfStack;
  484. for(auto unit : all)
  485. {
  486. healthOfStack[unit->unitId()] = unit->getAvailableHealth();
  487. }
  488. spells::BattleCast cast(&state, stack, spells::Mode::CREATURE_ACTIVE, ps.spell);
  489. cast.target = ps.dest;
  490. cast.cast(&state, rngStub);
  491. for(auto unit : all)
  492. {
  493. auto unitId = unit->unitId();
  494. auto localUnit = state.battleGetUnitByID(unitId);
  495. newHealthOfStack[unitId] = localUnit->getAvailableHealth();
  496. }
  497. int64_t totalGain = 0;
  498. for(auto unit : all)
  499. {
  500. auto unitId = unit->unitId();
  501. auto localUnit = state.battleGetUnitByID(unitId);
  502. auto healthDiff = newHealthOfStack[unitId] - healthOfStack[unitId];
  503. if(localUnit->unitOwner() != getCbc()->getPlayerID())
  504. healthDiff = -healthDiff;
  505. if(healthDiff < 0)
  506. {
  507. ps.value = -1;
  508. return; //do not damage own units at all
  509. }
  510. totalGain += healthDiff;
  511. }
  512. ps.value = totalGain;
  513. };
  514. int CBattleAI::distToNearestNeighbour(BattleHex hex, const ReachabilityInfo::TDistances &dists, BattleHex *chosenHex)
  515. {
  516. int ret = 1000000;
  517. for(BattleHex n : hex.neighbouringTiles())
  518. {
  519. if(dists[n] >= 0 && dists[n] < ret)
  520. {
  521. ret = dists[n];
  522. if(chosenHex)
  523. *chosenHex = n;
  524. }
  525. }
  526. return ret;
  527. }
  528. void CBattleAI::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool Side)
  529. {
  530. LOG_TRACE(logAi);
  531. side = Side;
  532. }
  533. bool CBattleAI::isCloser(const EnemyInfo &ei1, const EnemyInfo &ei2, const ReachabilityInfo::TDistances &dists)
  534. {
  535. return distToNearestNeighbour(ei1.s->getPosition(), dists) < distToNearestNeighbour(ei2.s->getPosition(), dists);
  536. }
  537. void CBattleAI::print(const std::string &text) const
  538. {
  539. logAi->trace("%s Battle AI[%p]: %s", playerID.getStr(), this, text);
  540. }
  541. boost::optional<BattleAction> CBattleAI::considerFleeingOrSurrendering()
  542. {
  543. if(cb->battleCanSurrender(playerID))
  544. {
  545. }
  546. if(cb->battleCanFlee())
  547. {
  548. }
  549. return boost::none;
  550. }