Nullkiller.cpp 18 KB

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