DefenceBehavior.cpp 7.9 KB

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