Nullkiller.cpp 17 KB

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