BattleAI.cpp 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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 "BattleEvaluator.h"
  13. #include "BattleExchangeVariant.h"
  14. #include "StackWithBonuses.h"
  15. #include "EnemyInfo.h"
  16. #include "tbb/parallel_for.h"
  17. #include "../../lib/CStopWatch.h"
  18. #include "../../lib/CThreadHelper.h"
  19. #include "../../lib/battle/CPlayerBattleCallback.h"
  20. #include "../../lib/callback/CBattleCallback.h"
  21. #include "../../lib/callback/IGameInfoCallback.h"
  22. #include "../../lib/mapObjects/CGTownInstance.h"
  23. #include "../../lib/spells/CSpellHandler.h"
  24. #include "../../lib/spells/ISpellMechanics.h"
  25. #include "../../lib/battle/BattleAction.h"
  26. #include "../../lib/battle/BattleStateInfoForRetreat.h"
  27. #include "../../lib/battle/CObstacleInstance.h"
  28. #include "../../lib/StartInfo.h"
  29. #include "../../lib/CStack.h" // TODO: remove
  30. // Eventually only IBattleInfoCallback and battle::Unit should be used,
  31. // CUnitState should be private and CStack should be removed completely
  32. #include "../../lib/logging/VisualLogger.h"
  33. #define LOGL(text) print(text)
  34. #define LOGFL(text, formattingEl) print(boost::str(boost::format(text) % formattingEl))
  35. CBattleAI::CBattleAI()
  36. : side(BattleSide::NONE),
  37. wasWaitingForRealize(false)
  38. {
  39. }
  40. CBattleAI::~CBattleAI()
  41. {
  42. if(cb)
  43. {
  44. //Restore previous state of CB - it may be shared with the main AI (like VCAI)
  45. cb->waitTillRealize = wasWaitingForRealize;
  46. }
  47. }
  48. void logHexNumbers()
  49. {
  50. #if BATTLE_TRACE_LEVEL >= 1
  51. logVisual->updateWithLock("hexes", [](IVisualLogBuilder & b)
  52. {
  53. for(BattleHex hex = BattleHex(0); hex < GameConstants::BFIELD_SIZE; ++hex)
  54. b.addText(hex, std::to_string(hex.toInt()));
  55. });
  56. #endif
  57. }
  58. void CBattleAI::initBattleInterface(std::shared_ptr<Environment> ENV, std::shared_ptr<CBattleCallback> CB)
  59. {
  60. env = ENV;
  61. cb = CB;
  62. playerID = *CB->getPlayerID();
  63. wasWaitingForRealize = CB->waitTillRealize;
  64. CB->waitTillRealize = false;
  65. movesSkippedByDefense = 0;
  66. logHexNumbers();
  67. }
  68. void CBattleAI::initBattleInterface(std::shared_ptr<Environment> ENV, std::shared_ptr<CBattleCallback> CB, AutocombatPreferences autocombatPreferences)
  69. {
  70. initBattleInterface(ENV, CB);
  71. autobattlePreferences = autocombatPreferences;
  72. }
  73. BattleAction CBattleAI::useHealingTent(const BattleID & battleID, const CStack *stack)
  74. {
  75. auto healingTargets = cb->getBattle(battleID)->battleGetStacks(CBattleInfoEssentials::ONLY_MINE);
  76. std::map<int, const CStack*> woundHpToStack;
  77. for(const auto * stack : healingTargets)
  78. {
  79. if(auto woundHp = stack->getMaxHealth() - stack->getFirstHPleft())
  80. woundHpToStack[woundHp] = stack;
  81. }
  82. if(woundHpToStack.empty())
  83. return BattleAction::makeDefend(stack);
  84. else
  85. return BattleAction::makeHeal(stack, woundHpToStack.rbegin()->second); //last element of the woundHpToStack is the most wounded stack
  86. }
  87. void CBattleAI::yourTacticPhase(const BattleID & battleID, int distance)
  88. {
  89. cb->battleMakeTacticAction(battleID, BattleAction::makeEndOFTacticPhase(cb->getBattle(battleID)->battleGetTacticsSide()));
  90. }
  91. static float getStrengthRatio(std::shared_ptr<CBattleInfoCallback> cb, BattleSide side)
  92. {
  93. auto stacks = cb->battleGetAllStacks();
  94. auto our = 0;
  95. auto enemy = 0;
  96. for(auto stack : stacks)
  97. {
  98. auto creature = stack->creatureId().toCreature();
  99. if(!creature)
  100. continue;
  101. if(stack->unitSide() == side)
  102. our += stack->getCount() * creature->getAIValue();
  103. else
  104. enemy += stack->getCount() * creature->getAIValue();
  105. }
  106. return enemy == 0 ? 1.0f : static_cast<float>(our) / enemy;
  107. }
  108. int getSimulationTurnsCount(const StartInfo * startInfo)
  109. {
  110. return startInfo->difficulty < 4 ? 2 : 10;
  111. }
  112. void CBattleAI::activeStack(const BattleID & battleID, const CStack * stack )
  113. {
  114. LOG_TRACE_PARAMS(logAi, "stack: %s", stack->nodeName());
  115. auto timeElapsed = [](std::chrono::time_point<std::chrono::high_resolution_clock> start) -> uint64_t
  116. {
  117. auto end = std::chrono::high_resolution_clock::now();
  118. return std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
  119. };
  120. BattleAction result = BattleAction::makeDefend(stack);
  121. auto start = std::chrono::high_resolution_clock::now();
  122. if(stack->creatureId() == CreatureID::CATAPULT)
  123. {
  124. cb->battleMakeUnitAction(battleID, useCatapult(battleID, stack));
  125. return;
  126. }
  127. if(stack->hasBonusOfType(BonusType::SIEGE_WEAPON) && stack->hasBonusOfType(BonusType::HEALER))
  128. {
  129. cb->battleMakeUnitAction(battleID, useHealingTent(battleID, stack));
  130. return;
  131. }
  132. #if BATTLE_TRACE_LEVEL>=1
  133. logAi->trace("Build evaluator and targets");
  134. #endif
  135. BattleEvaluator evaluator(
  136. env, cb, stack, playerID, battleID, side,
  137. getStrengthRatio(cb->getBattle(battleID), side),
  138. getSimulationTurnsCount(env->game()->getStartInfo()));
  139. result = evaluator.selectStackAction(stack);
  140. if(autobattlePreferences.enableSpellsUsage && evaluator.canCastSpell())
  141. {
  142. auto spelCasted = evaluator.attemptCastingSpell(stack);
  143. if(spelCasted)
  144. return;
  145. }
  146. logAi->trace("Spellcast attempt completed in %lld", timeElapsed(start));
  147. if(auto action = considerFleeingOrSurrendering(battleID))
  148. {
  149. cb->battleMakeUnitAction(battleID, *action);
  150. return;
  151. }
  152. if(result.actionType == EActionType::DEFEND)
  153. {
  154. movesSkippedByDefense++;
  155. }
  156. else if(result.actionType != EActionType::WAIT)
  157. {
  158. movesSkippedByDefense = 0;
  159. }
  160. logAi->trace("BattleAI decision made in %lld", timeElapsed(start));
  161. cb->battleMakeUnitAction(battleID, result);
  162. }
  163. BattleAction CBattleAI::useCatapult(const BattleID & battleID, const CStack * stack)
  164. {
  165. BattleAction attack;
  166. BattleHex targetHex = BattleHex::INVALID;
  167. if(cb->getBattle(battleID)->battleGetGateState() == EGateState::CLOSED)
  168. {
  169. targetHex = cb->getBattle(battleID)->wallPartToBattleHex(EWallPart::GATE);
  170. }
  171. else
  172. {
  173. std::array wallParts {
  174. EWallPart::KEEP,
  175. EWallPart::BOTTOM_TOWER,
  176. EWallPart::UPPER_TOWER,
  177. EWallPart::BELOW_GATE,
  178. EWallPart::OVER_GATE,
  179. EWallPart::BOTTOM_WALL,
  180. EWallPart::UPPER_WALL
  181. };
  182. for(auto wallPart : wallParts)
  183. {
  184. auto wallState = cb->getBattle(battleID)->battleGetWallState(wallPart);
  185. if(wallState != EWallState::NONE && wallState != EWallState::DESTROYED)
  186. {
  187. targetHex = cb->getBattle(battleID)->wallPartToBattleHex(wallPart);
  188. break;
  189. }
  190. }
  191. }
  192. if(!targetHex.isValid())
  193. {
  194. return BattleAction::makeDefend(stack);
  195. }
  196. attack.aimToHex(targetHex);
  197. attack.actionType = EActionType::CATAPULT;
  198. attack.side = side;
  199. attack.stackNumber = stack->unitId();
  200. movesSkippedByDefense = 0;
  201. return attack;
  202. }
  203. void CBattleAI::battleStart(const BattleID & battleID, const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, BattleSide Side, bool replayAllowed)
  204. {
  205. LOG_TRACE(logAi);
  206. side = Side;
  207. }
  208. void CBattleAI::print(const std::string &text) const
  209. {
  210. logAi->trace("%s Battle AI[%p]: %s", playerID.toString(), this, text);
  211. }
  212. std::optional<BattleAction> CBattleAI::considerFleeingOrSurrendering(const BattleID & battleID)
  213. {
  214. BattleStateInfoForRetreat bs;
  215. bs.canFlee = cb->getBattle(battleID)->battleCanFlee();
  216. bs.canSurrender = cb->getBattle(battleID)->battleCanSurrender(playerID);
  217. bs.ourSide = cb->getBattle(battleID)->battleGetMySide();
  218. bs.ourHero = cb->getBattle(battleID)->battleGetMyHero();
  219. bs.enemyHero = nullptr;
  220. for(auto stack : cb->getBattle(battleID)->battleGetAllStacks(false))
  221. {
  222. if(stack->alive())
  223. {
  224. if(stack->unitSide() == bs.ourSide)
  225. bs.ourStacks.push_back(stack);
  226. else
  227. {
  228. bs.enemyStacks.push_back(stack);
  229. bs.enemyHero = cb->getBattle(battleID)->battleGetOwnerHero(stack);
  230. }
  231. }
  232. }
  233. bs.turnsSkippedByDefense = movesSkippedByDefense / bs.ourStacks.size();
  234. if(!bs.canFlee && !bs.canSurrender)
  235. {
  236. return std::nullopt;
  237. }
  238. auto result = cb->makeSurrenderRetreatDecision(battleID, bs);
  239. if(!result && bs.canFlee && bs.turnsSkippedByDefense > 30)
  240. {
  241. return BattleAction::makeRetreat(bs.ourSide);
  242. }
  243. return result;
  244. }