Nullkiller.cpp 17 KB

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