Nullkiller.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  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->cbc = 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. 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(bool partialUpdate)
  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. if(!partialUpdate && pathfinderInvalidated)
  214. {
  215. memory->removeInvisibleObjects(cbc.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 : cbc->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() && cbc->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. int prioOfTask = 0;
  307. for (int prio = PriorityEvaluator::PriorityTier::INSTAKILL; prio <= PriorityEvaluator::PriorityTier::MAX_PRIORITY_TIER; ++prio)
  308. {
  309. prioOfTask = prio;
  310. selectedTasks = buildPlan(tasks, prio);
  311. if (!selectedTasks.empty() || settings->isUseFuzzy())
  312. break;
  313. }
  314. boost::range::sort(selectedTasks, [](const TTask& a, const TTask& b)
  315. {
  316. return a->priority > b->priority;
  317. });
  318. if(selectedTasks.empty())
  319. {
  320. selectedTasks.push_back(taskptr(Goals::Invalid()));
  321. }
  322. bool hasAnySuccess = false;
  323. for(const auto& selectedTask : selectedTasks)
  324. {
  325. if(cbc->getPlayerStatus(playerID) != EPlayerStatus::INGAME)
  326. return;
  327. if(!areAffectedObjectsPresent(selectedTask))
  328. {
  329. logAi->debug("Affected object not found. Canceling task.");
  330. continue;
  331. }
  332. std::string taskDescription = selectedTask->toString();
  333. HeroRole heroRole = getTaskRole(selectedTask);
  334. if(heroRole != HeroRole::MAIN || selectedTask->getHeroExchangeCount() <= 1)
  335. useHeroChain = false;
  336. // TODO: better to check turn distance here instead of priority
  337. if((heroRole != HeroRole::MAIN || selectedTask->priority < SMALL_SCAN_MIN_PRIORITY)
  338. && scanDepth == ScanDepth::MAIN_FULL)
  339. {
  340. useHeroChain = false;
  341. scanDepth = ScanDepth::SMALL;
  342. logAi->trace(
  343. "Goal %s has low priority %f so decreasing scan depth to gain performance.",
  344. taskDescription,
  345. selectedTask->priority);
  346. }
  347. if((settings->isUseFuzzy() && selectedTask->priority < MIN_PRIORITY) || (!settings->isUseFuzzy() && selectedTask->priority <= 0))
  348. {
  349. auto heroes = cbc->getHeroesInfo();
  350. const auto hasMp = vstd::contains_if(heroes, [](const CGHeroInstance * h) -> bool
  351. {
  352. return h->movementPointsRemaining() > 100;
  353. });
  354. if(hasMp && scanDepth != ScanDepth::ALL_FULL)
  355. {
  356. logAi->trace(
  357. "Goal %s has too low priority %f so increasing scan depth to full.",
  358. taskDescription,
  359. selectedTask->priority);
  360. scanDepth = ScanDepth::ALL_FULL;
  361. useHeroChain = false;
  362. hasAnySuccess = true;
  363. break;
  364. }
  365. logAi->trace("Goal %s has too low priority. It is not worth doing it.", taskDescription);
  366. continue;
  367. }
  368. #if NKAI_TRACE_LEVEL >= 1
  369. logAi->info("Pass %d: Performing prio %d task %s with prio: %d", i, prioOfTask, selectedTask->toString(), selectedTask->priority);
  370. #endif
  371. if(!executeTask(selectedTask))
  372. {
  373. if(hasAnySuccess)
  374. break;
  375. return;
  376. }
  377. hasAnySuccess = true;
  378. }
  379. hasAnySuccess |= handleTrading();
  380. if(!hasAnySuccess)
  381. {
  382. logAi->trace("Nothing was done this turn. Ending turn.");
  383. tracePlayerStatus(false);
  384. return;
  385. }
  386. for (const auto *heroInfo : cbc->getHeroesInfo())
  387. AIGateway::pickBestArtifacts(cbc, heroInfo);
  388. if(i == settings->getMaxPass())
  389. {
  390. logAi->warn("MaxPass reached. Terminating AI turn.");
  391. }
  392. }
  393. }
  394. bool Nullkiller::makeTurnHelperPriorityPass(Goals::TGoalVec & tempResults, int passIndex)
  395. {
  396. Goals::TTask bestPrioPassTask = taskptr(Goals::Invalid());
  397. for(int i = 1; i <= settings->getMaxPriorityPass() && cbc->getPlayerStatus(playerID) == EPlayerStatus::INGAME; i++)
  398. {
  399. tempResults.clear();
  400. decompose(tempResults, sptr(RecruitHeroBehavior()), 1);
  401. decompose(tempResults, sptr(BuyArmyBehavior()), 1);
  402. decompose(tempResults, sptr(BuildingBehavior()), 1);
  403. bestPrioPassTask = choseBestTask(tempResults);
  404. if(bestPrioPassTask->priority > 0)
  405. {
  406. #if NKAI_TRACE_LEVEL >= 1
  407. logAi->info("Pass %d: Performing priorityPass %d task %s with prio: %d", passIndex, i, bestPrioPassTask->toString(), bestPrioPassTask->priority);
  408. #endif
  409. if(!executeTask(bestPrioPassTask))
  410. return false;
  411. // TODO: Inspect why it's ok to do a partial update if condition is true
  412. updateState(bestPrioPassTask->getHero() == nullptr);
  413. }
  414. else
  415. {
  416. break;
  417. }
  418. if(i == settings->getMaxPriorityPass())
  419. {
  420. logAi->warn("MaxPriorityPass reached. Terminating priorityPass loop.");
  421. }
  422. }
  423. return true;
  424. }
  425. bool Nullkiller::areAffectedObjectsPresent(Goals::TTask task) const
  426. {
  427. auto affectedObjs = task->getAffectedObjects();
  428. for(auto oid : affectedObjs)
  429. {
  430. if(!cbc->getObj(oid, false))
  431. return false;
  432. }
  433. return true;
  434. }
  435. HeroRole Nullkiller::getTaskRole(Goals::TTask task) const
  436. {
  437. HeroPtr hero = task->getHero();
  438. HeroRole heroRole = HeroRole::MAIN;
  439. if(hero.validAndSet())
  440. heroRole = heroManager->getHeroRole(hero);
  441. return heroRole;
  442. }
  443. bool Nullkiller::executeTask(Goals::TTask task)
  444. {
  445. auto start = std::chrono::high_resolution_clock::now();
  446. std::string taskDescr = task->toString();
  447. makingTurnInterrupption.interruptionPoint();
  448. logAi->debug("Trying to realize %s (value %2.3f)", taskDescr, task->priority);
  449. try
  450. {
  451. task->accept(aiGw);
  452. logAi->trace("Task %s completed in %lld", taskDescr, timeElapsed(start));
  453. }
  454. catch(goalFulfilledException &)
  455. {
  456. logAi->trace("Task %s completed in %lld", taskDescr, timeElapsed(start));
  457. }
  458. catch(cannotFulfillGoalException & e)
  459. {
  460. logAi->error("Failed to realize subgoal of type %s, I will stop.", taskDescr);
  461. logAi->error("The error message was: %s", e.what());
  462. return false;
  463. }
  464. return true;
  465. }
  466. TResources Nullkiller::getFreeResources() const
  467. {
  468. auto freeRes = cbc->getResourceAmount() - lockedResources;
  469. freeRes.positive();
  470. return freeRes;
  471. }
  472. void Nullkiller::lockResources(const TResources & res)
  473. {
  474. lockedResources += res;
  475. }
  476. bool Nullkiller::handleTrading()
  477. {
  478. bool haveTraded = false;
  479. bool shouldTryToTrade = true;
  480. ObjectInstanceID marketId;
  481. for (auto town : cbc->getTownsInfo())
  482. {
  483. if (town->hasBuiltSomeTradeBuilding())
  484. {
  485. marketId = town->id;
  486. }
  487. }
  488. if (!marketId.hasValue())
  489. return false;
  490. if (const CGObjectInstance* obj = cbc->getObj(marketId, false))
  491. {
  492. if (const auto* m = dynamic_cast<const IMarket*>(obj))
  493. {
  494. while (shouldTryToTrade)
  495. {
  496. shouldTryToTrade = false;
  497. buildAnalyzer->update();
  498. TResources required = buildAnalyzer->getTotalResourcesRequired();
  499. TResources income = buildAnalyzer->getDailyIncome();
  500. TResources available = cbc->getResourceAmount();
  501. #if NKAI_TRACE_LEVEL >= 2
  502. logAi->debug("Available %s", available.toString());
  503. logAi->debug("Required %s", required.toString());
  504. #endif
  505. int mostWanted = -1;
  506. int mostExpendable = -1;
  507. float minRatio = std::numeric_limits<float>::max();
  508. float maxRatio = std::numeric_limits<float>::min();
  509. for (int i = 0; i < required.size(); ++i)
  510. {
  511. if (required[i] <= 0)
  512. continue;
  513. float ratio = static_cast<float>(available[i]) / required[i];
  514. if (ratio < minRatio) {
  515. minRatio = ratio;
  516. mostWanted = i;
  517. }
  518. }
  519. for (int i = 0; i < required.size(); ++i)
  520. {
  521. float ratio = available[i];
  522. if (required[i] > 0)
  523. ratio = static_cast<float>(available[i]) / required[i];
  524. else
  525. ratio = available[i];
  526. bool okToSell = false;
  527. if (i == GameResID::GOLD)
  528. {
  529. if (income[i] > 0 && !buildAnalyzer->isGoldPressureOverMax())
  530. okToSell = true;
  531. }
  532. else
  533. {
  534. if (required[i] <= 0 && income[i] > 0)
  535. okToSell = true;
  536. }
  537. if (ratio > maxRatio && okToSell) {
  538. maxRatio = ratio;
  539. mostExpendable = i;
  540. }
  541. }
  542. #if NKAI_TRACE_LEVEL >= 2
  543. logAi->debug("mostExpendable: %d mostWanted: %d", mostExpendable, mostWanted);
  544. #endif
  545. if (mostExpendable == mostWanted || mostWanted == -1 || mostExpendable == -1)
  546. return false;
  547. int toGive;
  548. int toGet;
  549. m->getOffer(mostExpendable, mostWanted, toGive, toGet, EMarketMode::RESOURCE_RESOURCE);
  550. //logAi->info("Offer is: I get %d of %s for %d of %s at %s", toGet, mostWanted, toGive, mostExpendable, obj->getObjectName());
  551. //TODO trade only as much as needed
  552. if (toGive && toGive <= available[mostExpendable]) //don't try to sell 0 resources
  553. {
  554. cbc->trade(m->getObjInstanceID(), EMarketMode::RESOURCE_RESOURCE, GameResID(mostExpendable), GameResID(mostWanted), toGive);
  555. #if NKAI_TRACE_LEVEL >= 2
  556. logAi->info("Traded %d of %s for %d of %s at %s", toGive, mostExpendable, toGet, mostWanted, obj->getObjectName());
  557. #endif
  558. haveTraded = true;
  559. shouldTryToTrade = true;
  560. }
  561. }
  562. }
  563. }
  564. return haveTraded;
  565. }
  566. std::shared_ptr<const CPathsInfo> Nullkiller::getPathsInfo(const CGHeroInstance * h) const
  567. {
  568. return pathfinderCache->getPathsInfo(h);
  569. }
  570. void Nullkiller::invalidatePaths()
  571. {
  572. pathfinderCache->invalidatePaths();
  573. }
  574. void Nullkiller::tracePlayerStatus(bool beginning) const
  575. {
  576. #if NKAI_TRACE_LEVEL >= 1
  577. float totalHeroesStrength = 0;
  578. int totalTownsLevel = 0;
  579. for (const auto *heroInfo : cbc->getHeroesInfo())
  580. {
  581. totalHeroesStrength += heroInfo->getTotalStrength();
  582. }
  583. for (const auto *townInfo : cbc->getTownsInfo())
  584. {
  585. totalTownsLevel += townInfo->getTownLevel();
  586. }
  587. const auto *firstWord = beginning ? "Beginning:" : "End:";
  588. logAi->info("%s totalHeroesStrength: %f, totalTownsLevel: %d, resources: %s", firstWord, totalHeroesStrength, totalTownsLevel, cbc->getResourceAmount().toString());
  589. #endif
  590. }
  591. }