BattleAI.cpp 8.0 KB

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