Nullkiller.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  1. /*
  2. * Nullkiller.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 "Nullkiller.h"
  12. #include <boost/range/algorithm/sort.hpp>
  13. #include "../AIGateway.h"
  14. #include "../Behaviors/CaptureObjectsBehavior.h"
  15. #include "../Behaviors/RecruitHeroBehavior.h"
  16. #include "../Behaviors/BuyArmyBehavior.h"
  17. #include "../Behaviors/StartupBehavior.h"
  18. #include "../Behaviors/DefenceBehavior.h"
  19. #include "../Behaviors/BuildingBehavior.h"
  20. #include "../Behaviors/GatherArmyBehavior.h"
  21. #include "../Behaviors/ClusterBehavior.h"
  22. #include "../Behaviors/StayAtTownBehavior.h"
  23. #include "../Behaviors/ExplorationBehavior.h"
  24. #include "../Goals/Invalid.h"
  25. #include "../Goals/Composition.h"
  26. #include "../../../lib/CPlayerState.h"
  27. #include "../../lib/StartInfo.h"
  28. #include "../../lib/pathfinder/PathfinderCache.h"
  29. #include "../../lib/pathfinder/PathfinderOptions.h"
  30. namespace NK2AI
  31. {
  32. using namespace Goals;
  33. // while we play vcmieagles graph can be shared
  34. std::unique_ptr<ObjectGraph> Nullkiller::baseGraph;
  35. Nullkiller::Nullkiller()
  36. : activeHero(nullptr)
  37. , scanDepth(ScanDepth::MAIN_FULL)
  38. , useHeroChain(true)
  39. , pathfinderInvalidated(false)
  40. , memory(std::make_unique<AIMemory>())
  41. {
  42. }
  43. Nullkiller::~Nullkiller() = default;
  44. bool canUseOpenMap(std::shared_ptr<CCallback> cb, PlayerColor playerID)
  45. {
  46. if(!cb->getStartInfo()->extraOptionsInfo.cheatsAllowed)
  47. {
  48. return false;
  49. }
  50. const TeamState * team = cb->getPlayerTeam(playerID);
  51. auto hasHumanInTeam = vstd::contains_if(team->players, [cb](PlayerColor teamMateID) -> bool
  52. {
  53. return cb->getPlayerState(teamMateID)->isHuman();
  54. });
  55. return !hasHumanInTeam;
  56. }
  57. void Nullkiller::init(std::shared_ptr<CCallback> cb, AIGateway * aiGw)
  58. {
  59. this->cc = cb;
  60. this->aiGw = aiGw;
  61. this->playerID = aiGw->playerID;
  62. settings = std::make_unique<Settings>(cb->getStartInfo()->difficulty);
  63. PathfinderOptions pathfinderOptions(*cb);
  64. pathfinderOptions.useTeleportTwoWay = true;
  65. pathfinderOptions.useTeleportOneWay = settings->isOneWayMonolithUsageAllowed();
  66. pathfinderOptions.useTeleportOneWayRandom = settings->isOneWayMonolithUsageAllowed();
  67. pathfinderCache = std::make_unique<PathfinderCache>(cb.get(), pathfinderOptions);
  68. if(canUseOpenMap(cb, playerID))
  69. {
  70. useObjectGraph = settings->isObjectGraphAllowed();
  71. openMap = settings->isOpenMap() || useObjectGraph;
  72. }
  73. else
  74. {
  75. useObjectGraph = false;
  76. openMap = false;
  77. }
  78. baseGraph.reset();
  79. priorityEvaluator.reset(new PriorityEvaluator(this));
  80. priorityEvaluators.reset(
  81. new SharedPool<PriorityEvaluator>(
  82. [&]()->std::unique_ptr<PriorityEvaluator>
  83. {
  84. return std::make_unique<PriorityEvaluator>(this);
  85. }));
  86. dangerHitMap.reset(new DangerHitMapAnalyzer(this));
  87. buildAnalyzer.reset(new BuildAnalyzer(this));
  88. objectClusterizer.reset(new ObjectClusterizer(this));
  89. dangerEvaluator.reset(new FuzzyHelper(this));
  90. pathfinder.reset(new AIPathfinder(cb.get(), this));
  91. armyManager.reset(new ArmyManager(cb.get(), this));
  92. heroManager.reset(new HeroManager(cb.get(), this));
  93. decomposer.reset(new DeepDecomposer(this));
  94. armyFormation.reset(new ArmyFormation(cb, this));
  95. }
  96. TaskPlanItem::TaskPlanItem(const TSubgoal & task)
  97. :task(task), affectedObjects(task->asTask()->getAffectedObjects())
  98. {
  99. }
  100. Goals::TTaskVec TaskPlan::getTasks() const
  101. {
  102. Goals::TTaskVec result;
  103. for(auto & item : tasks)
  104. {
  105. result.push_back(taskptr(*item.task));
  106. }
  107. vstd::removeDuplicates(result);
  108. return result;
  109. }
  110. void TaskPlan::merge(const TSubgoal & task)
  111. {
  112. TGoalVec blockers;
  113. if (task->asTask()->priority <= 0)
  114. return;
  115. for(auto & item : tasks)
  116. {
  117. for(auto objid : item.affectedObjects)
  118. {
  119. if(task == item.task || task->asTask()->isObjectAffected(objid) || (task->asTask()->getHero() != nullptr && task->asTask()->getHero() == item.task->asTask()->getHero()))
  120. {
  121. if(item.task->asTask()->priority >= task->asTask()->priority)
  122. return;
  123. blockers.push_back(item.task);
  124. break;
  125. }
  126. }
  127. }
  128. vstd::erase_if(tasks, [&](const TaskPlanItem & task2)
  129. {
  130. return vstd::contains(blockers, task2.task);
  131. });
  132. tasks.emplace_back(task);
  133. }
  134. Goals::TTask Nullkiller::choseBestTask(Goals::TGoalVec & tasks) const
  135. {
  136. if(tasks.empty())
  137. {
  138. return taskptr(Invalid());
  139. }
  140. for(const TSubgoal & task : tasks)
  141. {
  142. if(task->asTask()->priority <= 0)
  143. task->asTask()->priority = priorityEvaluator->evaluate(task);
  144. }
  145. auto bestTask = *vstd::maxElementByFun(tasks, [](const Goals::TSubgoal& task) -> float
  146. {
  147. return task->asTask()->priority;
  148. });
  149. return taskptr(*bestTask);
  150. }
  151. Goals::TTaskVec Nullkiller::buildPlan(TGoalVec & tasks, int priorityTier) const
  152. {
  153. TaskPlan taskPlan;
  154. tbb::parallel_for(tbb::blocked_range<size_t>(0, tasks.size()), [this, &tasks, priorityTier](const tbb::blocked_range<size_t> & r)
  155. {
  156. auto evaluator = this->priorityEvaluators->acquire();
  157. for(size_t i = r.begin(); i != r.end(); i++)
  158. {
  159. const auto & task = tasks[i];
  160. if (task->asTask()->priority <= 0 || priorityTier != PriorityEvaluator::PriorityTier::BUILDINGS)
  161. task->asTask()->priority = evaluator->evaluate(task, priorityTier);
  162. }
  163. });
  164. boost::range::sort(tasks, [](const TSubgoal& g1, const TSubgoal& g2) -> bool
  165. {
  166. return g2->asTask()->priority < g1->asTask()->priority;
  167. });
  168. for(const TSubgoal & task : tasks)
  169. {
  170. taskPlan.merge(task);
  171. }
  172. return taskPlan.getTasks();
  173. }
  174. void Nullkiller::decompose(Goals::TGoalVec & results, const Goals::TSubgoal& behavior, int decompositionMaxDepth) const
  175. {
  176. makingTurnInterrupption.interruptionPoint();
  177. logAi->debug("Decomposing behavior %s", behavior->toString());
  178. const auto start = std::chrono::high_resolution_clock::now();
  179. decomposer->decompose(results, behavior, decompositionMaxDepth);
  180. makingTurnInterrupption.interruptionPoint();
  181. logAi->debug("Decomposing behavior %s done in %ld", behavior->toString(), timeElapsed(start));
  182. }
  183. void Nullkiller::resetState()
  184. {
  185. std::unique_lock lockGuard(aiStateMutex);
  186. lockedResources = TResources();
  187. scanDepth = ScanDepth::MAIN_FULL;
  188. lockedHeroes.clear();
  189. dangerHitMap->resetHitmap();
  190. useHeroChain = true;
  191. objectClusterizer->reset();
  192. if(!baseGraph && isObjectGraphAllowed())
  193. {
  194. baseGraph = std::make_unique<ObjectGraph>();
  195. baseGraph->updateGraph(this);
  196. }
  197. }
  198. void Nullkiller::invalidatePathfinderData()
  199. {
  200. pathfinderInvalidated = true;
  201. }
  202. void Nullkiller::updateState()
  203. {
  204. makingTurnInterrupption.interruptionPoint();
  205. std::unique_lock lockGuard(aiStateMutex);
  206. auto start = std::chrono::high_resolution_clock::now();
  207. activeHero = nullptr;
  208. setTargetObject(-1);
  209. decomposer->reset();
  210. buildAnalyzer->update();
  211. if (!pathfinderInvalidated)
  212. logAi->trace("Skipping paths regeneration - up to date");
  213. else
  214. {
  215. memory->removeInvisibleObjects(cc.get());
  216. dangerHitMap->updateHitMap();
  217. dangerHitMap->calculateTileOwners();
  218. makingTurnInterrupption.interruptionPoint();
  219. heroManager->update();
  220. logAi->trace("Updating paths");
  221. std::map<const CGHeroInstance *, HeroRole> activeHeroes;
  222. for(auto hero : cc->getHeroesInfo())
  223. {
  224. if(getHeroLockedReason(hero) == HeroLockedReason::DEFENCE)
  225. continue;
  226. activeHeroes[hero] = heroManager->getHeroRole(hero);
  227. }
  228. PathfinderSettings cfg;
  229. cfg.useHeroChain = useHeroChain;
  230. cfg.allowBypassObjects = true;
  231. if(scanDepth == ScanDepth::SMALL || isObjectGraphAllowed())
  232. {
  233. cfg.mainTurnDistanceLimit = settings->getMainHeroTurnDistanceLimit();
  234. }
  235. if(scanDepth != ScanDepth::ALL_FULL || isObjectGraphAllowed())
  236. {
  237. cfg.scoutTurnDistanceLimit = settings->getScoutHeroTurnDistanceLimit();
  238. }
  239. makingTurnInterrupption.interruptionPoint();
  240. pathfinder->updatePaths(activeHeroes, cfg);
  241. if(isObjectGraphAllowed())
  242. {
  243. pathfinder->updateGraphs(
  244. activeHeroes,
  245. scanDepth == ScanDepth::SMALL ? 255 : 10,
  246. scanDepth == ScanDepth::ALL_FULL ? 255 : 3);
  247. }
  248. makingTurnInterrupption.interruptionPoint();
  249. objectClusterizer->clusterize();
  250. pathfinderInvalidated = false;
  251. }
  252. armyManager->update();
  253. logAi->debug("AI state updated in %ld ms", timeElapsed(start));
  254. }
  255. bool Nullkiller::isHeroLocked(const CGHeroInstance * hero) const
  256. {
  257. return getHeroLockedReason(hero) != HeroLockedReason::NOT_LOCKED;
  258. }
  259. bool Nullkiller::arePathHeroesLocked(const AIPath & path) const
  260. {
  261. if(getHeroLockedReason(path.targetHero) == HeroLockedReason::STARTUP)
  262. {
  263. #if NKAI_TRACE_LEVEL >= 1
  264. logAi->trace("Hero %s is locked by STARTUP. Discarding %s", path.targetHero->getObjectName(), path.toString());
  265. #endif
  266. return true;
  267. }
  268. for(auto & node : path.nodes)
  269. {
  270. auto lockReason = getHeroLockedReason(node.targetHero);
  271. if(lockReason != HeroLockedReason::NOT_LOCKED)
  272. {
  273. #if NKAI_TRACE_LEVEL >= 1
  274. logAi->trace("Hero %s is locked by %d. Discarding %s", path.targetHero->getObjectName(), (int)lockReason, path.toString());
  275. #endif
  276. return true;
  277. }
  278. }
  279. return false;
  280. }
  281. HeroLockedReason Nullkiller::getHeroLockedReason(const CGHeroInstance * hero) const
  282. {
  283. auto found = lockedHeroes.find(hero);
  284. return found != lockedHeroes.end() ? found->second : HeroLockedReason::NOT_LOCKED;
  285. }
  286. void Nullkiller::makeTurn()
  287. {
  288. std::lock_guard<std::mutex> sharedStorageLock(AISharedStorage::locker);
  289. const int MAX_DEPTH = 10;
  290. resetState();
  291. Goals::TGoalVec tasks;
  292. tracePlayerStatus(true);
  293. for(int i = 1; i <= settings->getMaxPass() && cc->getPlayerStatus(playerID) == EPlayerStatus::INGAME; i++)
  294. {
  295. updateState();
  296. if (!makeTurnHelperPriorityPass(tasks, i)) return;
  297. tasks.clear();
  298. decompose(tasks, sptr(CaptureObjectsBehavior()), 1);
  299. decompose(tasks, sptr(ClusterBehavior()), MAX_DEPTH);
  300. decompose(tasks, sptr(DefenceBehavior()), MAX_DEPTH);
  301. decompose(tasks, sptr(GatherArmyBehavior()), MAX_DEPTH);
  302. decompose(tasks, sptr(StayAtTownBehavior()), MAX_DEPTH);
  303. if(!isOpenMap())
  304. decompose(tasks, sptr(ExplorationBehavior()), MAX_DEPTH);
  305. TTaskVec selectedTasks;
  306. #if NKAI_TRACE_LEVEL >= 1
  307. int prioOfTask = 0;
  308. #endif
  309. for (int prio = PriorityEvaluator::PriorityTier::INSTAKILL; prio <= PriorityEvaluator::PriorityTier::MAX_PRIORITY_TIER; ++prio)
  310. {
  311. #if NKAI_TRACE_LEVEL >= 1
  312. prioOfTask = prio;
  313. #endif
  314. selectedTasks = buildPlan(tasks, prio);
  315. if (!selectedTasks.empty() || settings->isUseFuzzy())
  316. break;
  317. }
  318. boost::range::sort(selectedTasks, [](const TTask& a, const TTask& b)
  319. {
  320. return a->priority > b->priority;
  321. });
  322. if(selectedTasks.empty())
  323. {
  324. selectedTasks.push_back(taskptr(Goals::Invalid()));
  325. }
  326. bool hasAnySuccess = false;
  327. for(const auto& selectedTask : selectedTasks)
  328. {
  329. if(cc->getPlayerStatus(playerID) != EPlayerStatus::INGAME)
  330. return;
  331. if(!areAffectedObjectsPresent(selectedTask))
  332. {
  333. logAi->debug("Affected object not found. Canceling task.");
  334. continue;
  335. }
  336. std::string taskDescription = selectedTask->toString();
  337. HeroRole heroRole = getTaskRole(selectedTask);
  338. if(heroRole != HeroRole::MAIN || selectedTask->getHeroExchangeCount() <= 1)
  339. useHeroChain = false;
  340. // TODO: better to check turn distance here instead of priority
  341. if((heroRole != HeroRole::MAIN || selectedTask->priority < SMALL_SCAN_MIN_PRIORITY)
  342. && scanDepth == ScanDepth::MAIN_FULL)
  343. {
  344. useHeroChain = false;
  345. scanDepth = ScanDepth::SMALL;
  346. logAi->trace(
  347. "Goal %s has low priority %f so decreasing scan depth to gain performance.",
  348. taskDescription,
  349. selectedTask->priority);
  350. }
  351. if((settings->isUseFuzzy() && selectedTask->priority < MIN_PRIORITY) || (!settings->isUseFuzzy() && selectedTask->priority <= 0))
  352. {
  353. auto heroes = cc->getHeroesInfo();
  354. const auto hasMp = vstd::contains_if(heroes, [](const CGHeroInstance * h) -> bool
  355. {
  356. return h->movementPointsRemaining() > 100;
  357. });
  358. if(hasMp && scanDepth != ScanDepth::ALL_FULL)
  359. {
  360. logAi->trace(
  361. "Goal %s has too low priority %f so increasing scan depth to full.",
  362. taskDescription,
  363. selectedTask->priority);
  364. scanDepth = ScanDepth::ALL_FULL;
  365. useHeroChain = false;
  366. hasAnySuccess = true;
  367. break;
  368. }
  369. logAi->trace("Goal %s has too low priority. It is not worth doing it.", taskDescription);
  370. continue;
  371. }
  372. #if NKAI_TRACE_LEVEL >= 1
  373. logAi->info("Pass %d: Performing prio %d task %s with prio: %d", i, prioOfTask, selectedTask->toString(), selectedTask->priority);
  374. #endif
  375. if(!executeTask(selectedTask))
  376. {
  377. if(hasAnySuccess)
  378. break;
  379. return;
  380. }
  381. hasAnySuccess = true;
  382. }
  383. hasAnySuccess |= handleTrading();
  384. if(!hasAnySuccess)
  385. {
  386. logAi->trace("Nothing was done this turn. Ending turn.");
  387. tracePlayerStatus(false);
  388. return;
  389. }
  390. for (const auto *heroInfo : cc->getHeroesInfo())
  391. AIGateway::pickBestArtifacts(cc, heroInfo);
  392. if(i == settings->getMaxPass())
  393. {
  394. logAi->warn("MaxPass reached. Terminating AI turn.");
  395. }
  396. }
  397. }
  398. bool Nullkiller::makeTurnHelperPriorityPass(Goals::TGoalVec & tempResults, int passIndex)
  399. {
  400. Goals::TTask bestPrioPassTask = taskptr(Goals::Invalid());
  401. for(int i = 1; i <= settings->getMaxPriorityPass() && cc->getPlayerStatus(playerID) == EPlayerStatus::INGAME; i++)
  402. {
  403. tempResults.clear();
  404. // Call updateHitMap here instead of inside each of the 3 behaviors
  405. dangerHitMap->updateHitMap();
  406. decompose(tempResults, sptr(RecruitHeroBehavior()), 1);
  407. decompose(tempResults, sptr(BuyArmyBehavior()), 1);
  408. decompose(tempResults, sptr(BuildingBehavior()), 1);
  409. bestPrioPassTask = choseBestTask(tempResults);
  410. if(bestPrioPassTask->priority > 0)
  411. {
  412. #if NKAI_TRACE_LEVEL >= 1
  413. logAi->info("Pass %d: Performing priorityPass %d task %s with prio: %d", passIndex, i, bestPrioPassTask->toString(), bestPrioPassTask->priority);
  414. #endif
  415. if(!executeTask(bestPrioPassTask))
  416. return false;
  417. updateState();
  418. }
  419. else
  420. {
  421. break;
  422. }
  423. if(i == settings->getMaxPriorityPass())
  424. {
  425. logAi->warn("MaxPriorityPass reached. Terminating priorityPass loop.");
  426. }
  427. }
  428. return true;
  429. }
  430. bool Nullkiller::areAffectedObjectsPresent(Goals::TTask task) const
  431. {
  432. auto affectedObjs = task->getAffectedObjects();
  433. for(auto oid : affectedObjs)
  434. {
  435. if(!cc->getObj(oid, false))
  436. return false;
  437. }
  438. return true;
  439. }
  440. HeroRole Nullkiller::getTaskRole(Goals::TTask task) const
  441. {
  442. HeroPtr hero = task->getHero();
  443. HeroRole heroRole = HeroRole::MAIN;
  444. if(hero.validAndSet())
  445. heroRole = heroManager->getHeroRole(hero);
  446. return heroRole;
  447. }
  448. bool Nullkiller::executeTask(Goals::TTask task)
  449. {
  450. auto start = std::chrono::high_resolution_clock::now();
  451. std::string taskDescr = task->toString();
  452. makingTurnInterrupption.interruptionPoint();
  453. logAi->debug("Trying to realize %s (value %2.3f)", taskDescr, task->priority);
  454. try
  455. {
  456. task->accept(aiGw);
  457. logAi->trace("Task %s completed in %lld", taskDescr, timeElapsed(start));
  458. }
  459. catch(goalFulfilledException &)
  460. {
  461. logAi->trace("Task %s completed in %lld", taskDescr, timeElapsed(start));
  462. }
  463. catch(cannotFulfillGoalException & e)
  464. {
  465. logAi->error("Failed to realize subgoal of type %s, I will stop.", taskDescr);
  466. logAi->error("The error message was: %s", e.what());
  467. return false;
  468. }
  469. return true;
  470. }
  471. TResources Nullkiller::getFreeResources() const
  472. {
  473. auto freeRes = cc->getResourceAmount() - lockedResources;
  474. freeRes.positive();
  475. return freeRes;
  476. }
  477. void Nullkiller::lockResources(const TResources & res)
  478. {
  479. lockedResources += res;
  480. }
  481. bool Nullkiller::handleTrading()
  482. {
  483. bool haveTraded = false;
  484. bool shouldTryToTrade = true;
  485. ObjectInstanceID marketId;
  486. for (auto town : cc->getTownsInfo())
  487. {
  488. if (town->hasBuiltSomeTradeBuilding())
  489. {
  490. marketId = town->id;
  491. }
  492. }
  493. if (!marketId.hasValue())
  494. return false;
  495. if (const CGObjectInstance* obj = cc->getObj(marketId, false))
  496. {
  497. if (const auto* m = dynamic_cast<const IMarket*>(obj))
  498. {
  499. while (shouldTryToTrade)
  500. {
  501. shouldTryToTrade = false;
  502. buildAnalyzer->update();
  503. TResources required = buildAnalyzer->getTotalResourcesRequired();
  504. TResources income = buildAnalyzer->getDailyIncome();
  505. TResources available = cc->getResourceAmount();
  506. #if NKAI_TRACE_LEVEL >= 2
  507. logAi->debug("Available %s", available.toString());
  508. logAi->debug("Required %s", required.toString());
  509. #endif
  510. int mostWanted = -1;
  511. int mostExpendable = -1;
  512. float minRatio = std::numeric_limits<float>::max();
  513. float maxRatio = std::numeric_limits<float>::min();
  514. for (int i = 0; i < required.size(); ++i)
  515. {
  516. if (required[i] <= 0)
  517. continue;
  518. float ratio = static_cast<float>(available[i]) / required[i];
  519. if (ratio < minRatio) {
  520. minRatio = ratio;
  521. mostWanted = i;
  522. }
  523. }
  524. for (int i = 0; i < required.size(); ++i)
  525. {
  526. float ratio = available[i];
  527. if (required[i] > 0)
  528. ratio = static_cast<float>(available[i]) / required[i];
  529. else
  530. ratio = available[i];
  531. bool okToSell = false;
  532. if (i == GameResID::GOLD)
  533. {
  534. if (income[i] > 0 && !buildAnalyzer->isGoldPressureOverMax())
  535. okToSell = true;
  536. }
  537. else
  538. {
  539. if (required[i] <= 0 && income[i] > 0)
  540. okToSell = true;
  541. }
  542. if (ratio > maxRatio && okToSell) {
  543. maxRatio = ratio;
  544. mostExpendable = i;
  545. }
  546. }
  547. #if NKAI_TRACE_LEVEL >= 2
  548. logAi->debug("mostExpendable: %d mostWanted: %d", mostExpendable, mostWanted);
  549. #endif
  550. if (mostExpendable == mostWanted || mostWanted == -1 || mostExpendable == -1)
  551. return false;
  552. int toGive;
  553. int toGet;
  554. m->getOffer(mostExpendable, mostWanted, toGive, toGet, EMarketMode::RESOURCE_RESOURCE);
  555. //logAi->info("Offer is: I get %d of %s for %d of %s at %s", toGet, mostWanted, toGive, mostExpendable, obj->getObjectName());
  556. //TODO trade only as much as needed
  557. if (toGive && toGive <= available[mostExpendable]) //don't try to sell 0 resources
  558. {
  559. cc->trade(m->getObjInstanceID(), EMarketMode::RESOURCE_RESOURCE, GameResID(mostExpendable), GameResID(mostWanted), toGive);
  560. #if NKAI_TRACE_LEVEL >= 2
  561. logAi->info("Traded %d of %s for %d of %s at %s", toGive, mostExpendable, toGet, mostWanted, obj->getObjectName());
  562. #endif
  563. haveTraded = true;
  564. shouldTryToTrade = true;
  565. }
  566. }
  567. }
  568. }
  569. return haveTraded;
  570. }
  571. std::shared_ptr<const CPathsInfo> Nullkiller::getPathsInfo(const CGHeroInstance * h) const
  572. {
  573. return pathfinderCache->getPathsInfo(h);
  574. }
  575. void Nullkiller::invalidatePaths()
  576. {
  577. pathfinderCache->invalidatePaths();
  578. }
  579. void Nullkiller::tracePlayerStatus(bool beginning) const
  580. {
  581. #if NKAI_TRACE_LEVEL >= 1
  582. float totalHeroesStrength = 0;
  583. int totalTownsLevel = 0;
  584. for (const auto *heroInfo : cc->getHeroesInfo())
  585. {
  586. totalHeroesStrength += heroInfo->getTotalStrength();
  587. }
  588. for (const auto *townInfo : cc->getTownsInfo())
  589. {
  590. totalTownsLevel += townInfo->getTownLevel();
  591. }
  592. const auto *firstWord = beginning ? "Beginning:" : "End:";
  593. logAi->info("%s totalHeroesStrength: %f, totalTownsLevel: %d, resources: %s", firstWord, totalHeroesStrength, totalTownsLevel, cc->getResourceAmount().toString());
  594. #endif
  595. }
  596. }