Nullkiller.cpp 17 KB

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