DefenceBehavior.cpp 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. /*
  2. * DefenceBehavior.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 "DefenceBehavior.h"
  12. #include "../AIGateway.h"
  13. #include "../Engine/Nullkiller.h"
  14. #include "../AIUtility.h"
  15. #include "../Goals/BuyArmy.h"
  16. #include "../Goals/ExecuteHeroChain.h"
  17. #include "../Behaviors/CaptureObjectsBehavior.h"
  18. #include "../Goals/RecruitHero.h"
  19. #include "../Goals/DismissHero.h"
  20. #include "../Goals/Composition.h"
  21. #include "../Markers/DefendTown.h"
  22. #include "../Goals/ExchangeSwapTownHeroes.h"
  23. #include "lib/mapping/CMap.h" //for victory conditions
  24. #include "lib/CPathfinder.h"
  25. extern boost::thread_specific_ptr<CCallback> cb;
  26. extern boost::thread_specific_ptr<AIGateway> ai;
  27. using namespace Goals;
  28. std::string DefenceBehavior::toString() const
  29. {
  30. return "Defend towns";
  31. }
  32. Goals::TGoalVec DefenceBehavior::decompose() const
  33. {
  34. Goals::TGoalVec tasks;
  35. for(auto town : cb->getTownsInfo())
  36. {
  37. evaluateDefence(tasks, town);
  38. }
  39. return tasks;
  40. }
  41. void DefenceBehavior::evaluateDefence(Goals::TGoalVec & tasks, const CGTownInstance * town) const
  42. {
  43. logAi->debug("Evaluating defence for %s", town->name);
  44. auto treatNode = ai->nullkiller->dangerHitMap->getObjectTreat(town);
  45. auto treats = { treatNode.fastestDanger, treatNode.maximumDanger };
  46. if(!treatNode.fastestDanger.hero)
  47. {
  48. logAi->debug("No treat found for town %s", town->name);
  49. return;
  50. }
  51. int dayOfWeek = cb->getDate(Date::DAY_OF_WEEK);
  52. if(town->garrisonHero)
  53. {
  54. if(!ai->nullkiller->isHeroLocked(town->garrisonHero.get()))
  55. {
  56. if(!town->visitingHero && cb->getHeroesInfo().size() < GameConstants::MAX_HEROES_PER_PLAYER)
  57. {
  58. tasks.push_back(Goals::sptr(Goals::ExchangeSwapTownHeroes(town, nullptr).setpriority(5)));
  59. }
  60. return;
  61. }
  62. logAi->debug(
  63. "Hero %s in garrison of town %s is suposed to defend the town",
  64. town->garrisonHero->name,
  65. town->name);
  66. return;
  67. }
  68. uint64_t reinforcement = ai->nullkiller->armyManager->howManyReinforcementsCanBuy(town->getUpperArmy(), town);
  69. if(reinforcement)
  70. {
  71. logAi->debug("Town %s can buy defence army %lld", town->name, reinforcement);
  72. tasks.push_back(Goals::sptr(Goals::BuyArmy(town, reinforcement).setpriority(0.5f)));
  73. }
  74. auto paths = ai->nullkiller->pathfinder->getPathInfo(town->visitablePos());
  75. for(auto & treat : treats)
  76. {
  77. logAi->debug(
  78. "Town %s has treat %lld in %s turns, hero: %s",
  79. town->name,
  80. treat.danger,
  81. std::to_string(treat.turn),
  82. treat.hero->name);
  83. bool treatIsUnderControl = false;
  84. for(AIPath & path : paths)
  85. {
  86. if(path.getHeroStrength() > treat.danger)
  87. {
  88. if((path.turn() <= treat.turn && dayOfWeek + treat.turn < 6 && isSafeToVisit(path.targetHero, path.heroArmy, treat.danger))
  89. || (path.exchangeCount == 1 && path.turn() < treat.turn)
  90. || path.turn() < treat.turn - 1
  91. || (path.turn() < treat.turn && treat.turn >= 2))
  92. {
  93. logAi->debug(
  94. "Hero %s can eliminate danger for town %s using path %s.",
  95. path.targetHero->name,
  96. town->name,
  97. path.toString());
  98. treatIsUnderControl = true;
  99. break;
  100. }
  101. }
  102. }
  103. if(treatIsUnderControl)
  104. continue;
  105. if(!town->visitingHero
  106. && town->hasBuilt(BuildingID::TAVERN)
  107. && cb->getResourceAmount(Res::GOLD) > GameConstants::HERO_GOLD_COST)
  108. {
  109. auto heroesInTavern = cb->getAvailableHeroes(town);
  110. for(auto hero : heroesInTavern)
  111. {
  112. if(hero->getTotalStrength() > treat.danger)
  113. {
  114. auto myHeroes = cb->getHeroesInfo();
  115. if(cb->getHeroesInfo().size() < ALLOWED_ROAMING_HEROES)
  116. {
  117. logAi->debug("Hero %s can be recruited to defend %s", hero->name, town->name);
  118. tasks.push_back(Goals::sptr(Goals::RecruitHero(town, hero).setpriority(1)));
  119. continue;
  120. }
  121. else
  122. {
  123. const CGHeroInstance * weakestHero = nullptr;
  124. for(auto existingHero : myHeroes)
  125. {
  126. if(ai->nullkiller->isHeroLocked(existingHero)
  127. || existingHero->getArmyStrength() > hero->getArmyStrength()
  128. || ai->nullkiller->heroManager->getHeroRole(existingHero) == HeroRole::MAIN
  129. || existingHero->movement
  130. || existingHero->artifactsWorn.size() > (existingHero->hasSpellbook() ? 2 : 1))
  131. continue;
  132. if(!weakestHero || weakestHero->getFightingStrength() > existingHero->getFightingStrength())
  133. {
  134. weakestHero = existingHero;
  135. }
  136. if(weakestHero)
  137. {
  138. tasks.push_back(Goals::sptr(Goals::DismissHero(weakestHero)));
  139. }
  140. }
  141. }
  142. }
  143. }
  144. }
  145. if(paths.empty())
  146. {
  147. logAi->debug("No ways to defend town %s", town->name);
  148. continue;
  149. }
  150. std::vector<int> pathsToDefend;
  151. std::map<const CGHeroInstance *, std::vector<int>> defferedPaths;
  152. for(int i = 0; i < paths.size(); i++)
  153. {
  154. auto & path = paths[i];
  155. #if AI_TRACE_LEVEL >= 1
  156. logAi->trace(
  157. "Hero %s can defend town with force %lld in %s turns, cost: %f, path: %s",
  158. path.targetHero->name,
  159. path.getHeroStrength(),
  160. std::to_string(path.turn()),
  161. path.movementCost(),
  162. path.toString());
  163. #endif
  164. if(path.turn() <= treat.turn - 2)
  165. {
  166. logAi->trace("Deffer defence of %s by %s because he has enough time to rich the town next trun",
  167. town->name,
  168. path.targetHero->name);
  169. defferedPaths[path.targetHero].push_back(i);
  170. continue;
  171. }
  172. if(path.targetHero == town->visitingHero && path.exchangeCount == 1)
  173. {
  174. #if AI_TRACE_LEVEL >= 1
  175. logAi->trace("Put %s to garrison of town %s",
  176. path.targetHero->name,
  177. town->name);
  178. #endif
  179. // dismiss creatures we are not able to pick to be able to hide in garrison
  180. if(town->garrisonHero
  181. || town->getUpperArmy()->stacksCount() == 0
  182. || (town->getUpperArmy()->getArmyStrength() < 500 && town->fortLevel() >= CGTownInstance::CITADEL))
  183. {
  184. tasks.push_back(
  185. Goals::sptr(Composition()
  186. .addNext(DefendTown(town, treat, path.targetHero))
  187. .addNext(ExchangeSwapTownHeroes(town, town->visitingHero.get(), HeroLockedReason::DEFENCE))));
  188. }
  189. continue;
  190. }
  191. if(treat.turn == 0 || (path.turn() <= treat.turn && path.getHeroStrength() * SAFE_ATTACK_CONSTANT >= treat.danger))
  192. {
  193. if(ai->nullkiller->arePathHeroesLocked(path))
  194. {
  195. #if AI_TRACE_LEVEL >= 1
  196. logAi->trace("Can not move %s to defend town %s. Path is locked.",
  197. path.targetHero->name,
  198. town->name);
  199. #endif
  200. continue;
  201. }
  202. pathsToDefend.push_back(i);
  203. }
  204. }
  205. for(int i : pathsToDefend)
  206. {
  207. AIPath & path = paths[i];
  208. for(int j : defferedPaths[path.targetHero])
  209. {
  210. AIPath & defferedPath = paths[j];
  211. if(defferedPath.getHeroStrength() >= path.getHeroStrength()
  212. && defferedPath.turn() <= path.turn())
  213. {
  214. continue;
  215. }
  216. }
  217. #if AI_TRACE_LEVEL >= 1
  218. logAi->trace("Move %s to defend town %s",
  219. path.targetHero->name,
  220. town->name);
  221. #endif
  222. Composition composition;
  223. composition.addNext(DefendTown(town, treat, path)).addNext(ExecuteHeroChain(path, town));
  224. auto firstBlockedAction = path.getFirstBlockedAction();
  225. if(firstBlockedAction)
  226. {
  227. auto subGoal = firstBlockedAction->decompose(path.targetHero);
  228. #if AI_TRACE_LEVEL >= 2
  229. logAi->trace("Decomposing special action %s returns %s", firstBlockedAction->toString(), subGoal->toString());
  230. #endif
  231. if(subGoal->invalid())
  232. {
  233. #if AI_TRACE_LEVEL >= 1
  234. logAi->trace("Path is invalid. Skipping");
  235. #endif
  236. continue;
  237. }
  238. composition.addNext(subGoal);
  239. }
  240. tasks.push_back(Goals::sptr(composition));
  241. }
  242. }
  243. logAi->debug("Found %d tasks", tasks.size());
  244. }