Goals.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  1. #include "StdInc.h"
  2. #include "Goals.h"
  3. #include "VCAI.h"
  4. /*
  5. * Goals.cpp, part of VCMI engine
  6. *
  7. * Authors: listed in file AUTHORS in main folder
  8. *
  9. * License: GNU General Public License v2.0 or later
  10. * Full text of license available in license.txt file, in main folder
  11. *
  12. */
  13. extern boost::thread_specific_ptr<CCallback> cb;
  14. extern boost::thread_specific_ptr<VCAI> ai;
  15. using namespace vstd;
  16. using namespace Goals;
  17. std::string Goals::CGoal::name() const //TODO: virtualize
  18. {
  19. switch (goalType)
  20. {
  21. case INVALID:
  22. return "INVALID";
  23. case WIN:
  24. return "WIN";
  25. case DO_NOT_LOSE:
  26. return "DO NOT LOOSE";
  27. case CONQUER:
  28. return "CONQUER";
  29. case BUILD:
  30. return "BUILD";
  31. case EXPLORE:
  32. return "EXPLORE";
  33. case GATHER_ARMY:
  34. return "GATHER ARMY";
  35. case BOOST_HERO:
  36. return "BOOST_HERO (unsupported)";
  37. case RECRUIT_HERO:
  38. return "RECRUIT HERO";
  39. case BUILD_STRUCTURE:
  40. return "BUILD STRUCTURE";
  41. case COLLECT_RES:
  42. return "COLLECT RESOURCE";
  43. case GATHER_TROOPS:
  44. return "GATHER TROOPS";
  45. case GET_OBJ:
  46. return "GET OBJECT " + boost::lexical_cast<std::string>(objid);
  47. case FIND_OBJ:
  48. return "FIND OBJECT " + boost::lexical_cast<std::string>(objid);
  49. case VISIT_HERO:
  50. return "VISIT HERO " + boost::lexical_cast<std::string>(objid);
  51. case GET_ART_TYPE:
  52. return "GET ARTIFACT OF TYPE " + VLC->arth->artifacts[aid]->Name();
  53. case ISSUE_COMMAND:
  54. return "ISSUE COMMAND (unsupported)";
  55. case VISIT_TILE:
  56. return "VISIT TILE " + tile();
  57. case CLEAR_WAY_TO:
  58. return "CLEAR WAY TO " + tile();
  59. case DIG_AT_TILE:
  60. return "DIG AT TILE " + tile();
  61. default:
  62. return boost::lexical_cast<std::string>(goalType);
  63. }
  64. }
  65. #define I_AM_ELEMENTAR return make_shared<Goals::CGoal>(setisElementar(true))
  66. TSubgoal Win::whatToDoToAchieve()
  67. {
  68. const VictoryCondition &vc = cb->getMapHeader()->victoryCondition;
  69. EVictoryConditionType::EVictoryConditionType cond = vc.condition;
  70. if(!vc.appliesToAI)
  71. {
  72. //TODO deduce victory from human loss condition
  73. cond = EVictoryConditionType::WINSTANDARD;
  74. }
  75. switch(cond)
  76. {
  77. case EVictoryConditionType::ARTIFACT:
  78. return make_shared<Goals::CGoal> (Goals::GetArtOfType().setaid(vc.objectId));
  79. case EVictoryConditionType::BEATHERO:
  80. return make_shared<Goals::CGoal> (Goals::GetObj(vc.obj->id.getNum()));
  81. case EVictoryConditionType::BEATMONSTER:
  82. return make_shared<Goals::CGoal> (Goals::GetObj(vc.obj->id.getNum()));
  83. case EVictoryConditionType::BUILDCITY:
  84. //TODO build castle/capitol
  85. break;
  86. case EVictoryConditionType::BUILDGRAIL:
  87. {
  88. if(auto h = ai->getHeroWithGrail())
  89. {
  90. //hero is in a town that can host Grail
  91. if(h->visitedTown && !vstd::contains(h->visitedTown->forbiddenBuildings, BuildingID::GRAIL))
  92. {
  93. const CGTownInstance *t = h->visitedTown;
  94. return make_shared<Goals::CGoal> (Goals::BuildThis().setbid(BuildingID::GRAIL).settown(t));
  95. }
  96. else
  97. {
  98. auto towns = cb->getTownsInfo();
  99. towns.erase(boost::remove_if(towns,
  100. [](const CGTownInstance *t) -> bool
  101. {
  102. return vstd::contains(t->forbiddenBuildings, BuildingID::GRAIL);
  103. }),
  104. towns.end());
  105. boost::sort(towns, isCloser);
  106. if(towns.size())
  107. {
  108. return make_shared<Goals::CGoal> (Goals::VisitTile(towns.front()->visitablePos()).sethero(h));
  109. }
  110. }
  111. }
  112. double ratio = 0;
  113. int3 grailPos = cb->getGrailPos(ratio);
  114. if(ratio > 0.99)
  115. {
  116. return make_shared<Goals::CGoal> (Goals::DigAtTile().settile(grailPos));
  117. } //TODO: use FIND_OBJ
  118. else if(const CGObjectInstance * obj = ai->getUnvisitedObj(objWithID<Obj::OBELISK>)) //there are unvisited Obelisks
  119. {
  120. return make_shared<Goals::CGoal> (Goals::GetObj(obj->id.getNum()));
  121. }
  122. else
  123. return make_shared<Goals::CGoal> (Goals::Explore());
  124. }
  125. break;
  126. case EVictoryConditionType::CAPTURECITY:
  127. return make_shared<Goals::CGoal> (Goals::GetObj(vc.obj->id.getNum()));
  128. case EVictoryConditionType::GATHERRESOURCE:
  129. return make_shared<Goals::CGoal> (Goals::CollectRes().setresID(static_cast<Res::ERes>(vc.objectId)).setvalue(vc.count));
  130. //TODO mines? piles? marketplace?
  131. //save?
  132. break;
  133. case EVictoryConditionType::GATHERTROOP:
  134. return make_shared<Goals::CGoal> (Goals::GatherTroops().setobjid(vc.objectId).setvalue(vc.count));
  135. break;
  136. case EVictoryConditionType::TAKEDWELLINGS:
  137. break;
  138. case EVictoryConditionType::TAKEMINES:
  139. break;
  140. case EVictoryConditionType::TRANSPORTITEM:
  141. break;
  142. case EVictoryConditionType::WINSTANDARD:
  143. return make_shared<Goals::CGoal> (Goals::Conquer());
  144. default:
  145. assert(0);
  146. }
  147. return make_shared<Goals::CGoal> (Goals::INVALID);
  148. }
  149. TSubgoal FindObj::whatToDoToAchieve()
  150. {
  151. const CGObjectInstance * o = nullptr;
  152. if (resID > -1) //specified
  153. {
  154. for(const CGObjectInstance *obj : ai->visitableObjs)
  155. {
  156. if(obj->ID == objid && obj->subID == resID)
  157. {
  158. o = obj;
  159. break; //TODO: consider multiple objects and choose best
  160. }
  161. }
  162. }
  163. else
  164. {
  165. for(const CGObjectInstance *obj : ai->visitableObjs)
  166. {
  167. if(obj->ID == objid)
  168. {
  169. o = obj;
  170. break; //TODO: consider multiple objects and choose best
  171. }
  172. }
  173. }
  174. if (o && isReachable(o))
  175. return make_shared<Goals::CGoal> (Goals::GetObj(o->id.getNum()));
  176. else
  177. return make_shared<Goals::CGoal> (Goals::Explore());
  178. }
  179. TSubgoal GetObj::whatToDoToAchieve()
  180. {
  181. const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(objid));
  182. if(!obj)
  183. return make_shared<Goals::CGoal> (Goals::Explore());
  184. int3 pos = obj->visitablePos();
  185. return make_shared<Goals::CGoal> (Goals::VisitTile(pos));
  186. }
  187. TSubgoal VisitHero::whatToDoToAchieve()
  188. {
  189. const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(objid));
  190. if(!obj)
  191. return make_shared<Goals::CGoal> (Goals::Explore());
  192. int3 pos = obj->visitablePos();
  193. if (hero && ai->isAccessibleForHero(pos, hero, true) && isSafeToVisit(hero, pos)) //enemy heroes can get reinforcements
  194. return make_shared<Goals::CGoal> (settile(pos).setisElementar(true));
  195. return make_shared<Goals::CGoal> (Goals::INVALID);
  196. }
  197. TSubgoal GetArtOfType::whatToDoToAchieve()
  198. {
  199. TSubgoal alternativeWay = CGoal::lookForArtSmart(aid); //TODO: use
  200. if(alternativeWay->invalid())
  201. return make_shared<Goals::CGoal> (Goals::FindObj(Obj::ARTIFACT, aid));
  202. return make_shared<Goals::CGoal> (Goals::INVALID);
  203. }
  204. TSubgoal ClearWayTo::whatToDoToAchieve()
  205. {
  206. assert(tile.x >= 0); //set tile
  207. if(!cb->isVisible(tile))
  208. {
  209. logAi->errorStream() << "Clear way should be used with visible tiles!";
  210. return make_shared<Goals::CGoal> (Goals::Explore());
  211. }
  212. HeroPtr h = hero ? hero : ai->primaryHero();
  213. if(!h)
  214. return make_shared<Goals::CGoal> (Goals::RecruitHero());
  215. cb->setSelection(*h);
  216. SectorMap sm;
  217. bool dropToFile = false;
  218. if(dropToFile) //for debug purposes
  219. sm.write("test.txt");
  220. int3 tileToHit = sm.firstTileToGet(h, tile);
  221. //if(isSafeToVisit(h, tileToHit))
  222. if(isBlockedBorderGate(tileToHit))
  223. { //FIXME: this way we'll not visit gate and activate quest :?
  224. return make_shared<Goals::CGoal> (Goals::FindObj (Obj::KEYMASTER, cb->getTile(tileToHit)->visitableObjects.back()->subID));
  225. }
  226. //FIXME: this code shouldn't be necessary
  227. if(tileToHit == tile)
  228. {
  229. logAi->errorStream() << boost::format("Very strange, tile to hit is %s and tile is also %s, while hero %s is at %s\n")
  230. % tileToHit % tile % h->name % h->visitablePos();
  231. throw cannotFulfillGoalException("Retrieving first tile to hit failed (probably)!");
  232. }
  233. auto topObj = backOrNull(cb->getVisitableObjs(tileToHit));
  234. if(topObj && topObj->ID == Obj::HERO && cb->getPlayerRelations(h->tempOwner, topObj->tempOwner) != PlayerRelations::ENEMIES)
  235. {
  236. std::string problem = boost::str(boost::format("%s stands in the way of %s.\n") % topObj->getHoverText() % h->getHoverText());
  237. throw cannotFulfillGoalException(problem);
  238. }
  239. return make_shared<Goals::CGoal> (Goals::VisitTile(tileToHit).sethero(h));
  240. //FIXME:: attempts to visit completely unreachable tile with hero results in stall
  241. //TODO czy istnieje lepsza droga?
  242. throw cannotFulfillGoalException("Cannot reach given tile!"); //how and when could this be used?
  243. }
  244. TSubgoal Explore::whatToDoToAchieve()
  245. {
  246. auto objs = ai->visitableObjs; //try to use buildings that uncover map
  247. erase_if(objs, [&](const CGObjectInstance *obj) -> bool
  248. {
  249. if (vstd::contains(ai->alreadyVisited, obj))
  250. return true;
  251. switch (obj->ID.num)
  252. {
  253. case Obj::REDWOOD_OBSERVATORY:
  254. case Obj::PILLAR_OF_FIRE:
  255. case Obj::CARTOGRAPHER:
  256. case Obj::SUBTERRANEAN_GATE: //TODO: check ai->knownSubterraneanGates
  257. //case Obj::MONOLITH1:
  258. //case obj::MONOLITH2:
  259. //case obj::MONOLITH3:
  260. //case Obj::WHIRLPOOL:
  261. return false; //do not erase
  262. break;
  263. default:
  264. return true;
  265. }
  266. });
  267. if (objs.size())
  268. {
  269. if (hero.get(true))
  270. {
  271. for (auto obj : objs)
  272. {
  273. auto pos = obj->visitablePos();
  274. //FIXME: this confition fails if everything but guarded subterranen gate was explored. in this case we should gather army for hero
  275. if (isSafeToVisit(hero, pos) && ai->isAccessibleForHero(pos, hero))
  276. return make_shared<Goals::CGoal> (Goals::VisitTile(pos).sethero(hero));
  277. }
  278. }
  279. else
  280. {
  281. for (auto obj : objs)
  282. {
  283. auto pos = obj->visitablePos();
  284. if (ai->isAccessible (pos)) //TODO: check safety?
  285. return make_shared<Goals::CGoal> (Goals::VisitTile(pos).sethero(hero));
  286. }
  287. }
  288. }
  289. if (hero)
  290. {
  291. int3 t = whereToExplore(hero);
  292. if (t.z == -1) //no safe tile to explore - we need to break!
  293. {
  294. erase_if (objs, [&](const CGObjectInstance *obj) -> bool
  295. {
  296. switch (obj->ID.num)
  297. {
  298. case Obj::CARTOGRAPHER:
  299. case Obj::SUBTERRANEAN_GATE:
  300. //case Obj::MONOLITH1:
  301. //case obj::MONOLITH2:
  302. //case obj::MONOLITH3:
  303. //case Obj::WHIRLPOOL:
  304. return false; //do not erase
  305. break;
  306. default:
  307. return true;
  308. }
  309. });
  310. if (objs.size())
  311. {
  312. return make_shared<Goals::CGoal> (Goals::VisitTile(objs.front()->visitablePos()).sethero(hero).setisAbstract(true));
  313. }
  314. else
  315. throw cannotFulfillGoalException("Cannot explore - no possible ways found!");
  316. }
  317. return make_shared<Goals::CGoal> (Goals::VisitTile(t).sethero(hero));
  318. }
  319. auto hs = cb->getHeroesInfo();
  320. int howManyHeroes = hs.size();
  321. erase(hs, [](const CGHeroInstance *h)
  322. {
  323. return contains(ai->lockedHeroes, h);
  324. });
  325. if(hs.empty()) //all heroes are busy. buy new one
  326. {
  327. if (howManyHeroes < 3 && ai->findTownWithTavern()) //we may want to recruit second hero. TODO: make it smart finally
  328. return make_shared<Goals::CGoal> (Goals::RecruitHero());
  329. else //find mobile hero with weakest army
  330. {
  331. hs = cb->getHeroesInfo();
  332. erase_if(hs, [](const CGHeroInstance *h)
  333. {
  334. return !h->movement; //only hero with movement are of interest for us
  335. });
  336. if (hs.empty())
  337. {
  338. if (howManyHeroes < GameConstants::MAX_HEROES_PER_PLAYER)
  339. return make_shared<Goals::CGoal> (Goals::RecruitHero());
  340. else
  341. throw cannotFulfillGoalException("No heroes with remaining MPs for exploring!\n");
  342. }
  343. boost::sort(hs, compareMovement); //closer to what?
  344. }
  345. }
  346. const CGHeroInstance *h = hs.front();
  347. return make_shared<Goals::CGoal> (sethero(h).setisAbstract(true));
  348. I_AM_ELEMENTAR; //FIXME: how can this be called?
  349. };
  350. TSubgoal RecruitHero::whatToDoToAchieve()
  351. {
  352. const CGTownInstance *t = ai->findTownWithTavern();
  353. if(!t)
  354. return make_shared<Goals::CGoal> (Goals::BuildThis().setbid(BuildingID::TAVERN));
  355. if(cb->getResourceAmount(Res::GOLD) < HERO_GOLD_COST)
  356. return make_shared<Goals::CGoal> (Goals::CollectRes().setresID(Res::GOLD).setvalue(HERO_GOLD_COST));
  357. I_AM_ELEMENTAR;
  358. }
  359. TSubgoal VisitTile::whatToDoToAchieve()
  360. {
  361. if(!cb->isVisible(tile))
  362. return make_shared<Goals::CGoal> (Goals::Explore());
  363. if(hero && !ai->isAccessibleForHero(tile, hero))
  364. hero = nullptr;
  365. if(!hero)
  366. {
  367. if(cb->getHeroesInfo().empty())
  368. {
  369. return make_shared<Goals::CGoal> (Goals::RecruitHero());
  370. }
  371. for(const CGHeroInstance *h : cb->getHeroesInfo())
  372. {
  373. if(ai->isAccessibleForHero(tile, h))
  374. {
  375. hero = h;
  376. break;
  377. }
  378. }
  379. }
  380. if(hero)
  381. {
  382. if(isSafeToVisit(hero, tile))
  383. return make_shared<Goals::CGoal>(setisElementar(true));
  384. else
  385. {
  386. return make_shared<Goals::CGoal>(Goals::GatherArmy().sethero(hero).setvalue(evaluateDanger(tile, *hero) * SAFE_ATTACK_CONSTANT)); //TODO: should it be abstract?
  387. }
  388. }
  389. else //inaccessible for all heroes
  390. {
  391. return make_shared<Goals::CGoal>(Goals::ClearWayTo(tile));
  392. }
  393. }
  394. TSubgoal DigAtTile::whatToDoToAchieve()
  395. {
  396. const CGObjectInstance *firstObj = frontOrNull(cb->getVisitableObjs(tile));
  397. if(firstObj && firstObj->ID == Obj::HERO && firstObj->tempOwner == ai->playerID) //we have hero at dest
  398. {
  399. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(firstObj);
  400. return make_shared<Goals::CGoal> (sethero(h).setisElementar(true));
  401. }
  402. return make_shared<Goals::CGoal>(Goals::VisitTile(tile));
  403. }
  404. TSubgoal BuildThis::whatToDoToAchieve()
  405. {
  406. //TODO check res
  407. //look for town
  408. //prerequisites?
  409. I_AM_ELEMENTAR;
  410. }
  411. TSubgoal CollectRes::whatToDoToAchieve()
  412. {
  413. std::vector<const IMarket*> markets;
  414. std::vector<const CGObjectInstance*> visObjs;
  415. ai->retreiveVisitableObjs(visObjs, true);
  416. for(const CGObjectInstance *obj : visObjs)
  417. {
  418. if(const IMarket *m = IMarket::castFrom(obj, false))
  419. {
  420. if(obj->ID == Obj::TOWN && obj->tempOwner == ai->playerID && m->allowsTrade(EMarketMode::RESOURCE_RESOURCE))
  421. markets.push_back(m);
  422. else if(obj->ID == Obj::TRADING_POST) //TODO a moze po prostu test na pozwalanie handlu?
  423. markets.push_back(m);
  424. }
  425. }
  426. boost::sort(markets, [](const IMarket *m1, const IMarket *m2) -> bool
  427. {
  428. return m1->getMarketEfficiency() < m2->getMarketEfficiency();
  429. });
  430. markets.erase(boost::remove_if(markets, [](const IMarket *market) -> bool
  431. {
  432. return !(market->o->ID == Obj::TOWN && market->o->tempOwner == ai->playerID)
  433. && !ai->isAccessible(market->o->visitablePos());
  434. }),markets.end());
  435. if(!markets.size())
  436. {
  437. for(const CGTownInstance *t : cb->getTownsInfo())
  438. {
  439. if(cb->canBuildStructure(t, BuildingID::MARKETPLACE) == EBuildingState::ALLOWED)
  440. return make_shared<Goals::CGoal>(Goals::BuildThis().settown(t).setbid(BuildingID::MARKETPLACE));
  441. }
  442. }
  443. else
  444. {
  445. const IMarket *m = markets.back();
  446. //attempt trade at back (best prices)
  447. int howManyCanWeBuy = 0;
  448. for(Res::ERes i = Res::WOOD; i <= Res::GOLD; vstd::advance(i, 1))
  449. {
  450. if(i == resID) continue;
  451. int toGive = -1, toReceive = -1;
  452. m->getOffer(i, resID, toGive, toReceive, EMarketMode::RESOURCE_RESOURCE);
  453. assert(toGive > 0 && toReceive > 0);
  454. howManyCanWeBuy += toReceive * (cb->getResourceAmount(i) / toGive);
  455. }
  456. if(howManyCanWeBuy + cb->getResourceAmount(static_cast<Res::ERes>(resID)) >= value)
  457. {
  458. auto backObj = backOrNull(cb->getVisitableObjs(m->o->visitablePos())); //it'll be a hero if we have one there; otherwise marketplace
  459. assert(backObj);
  460. if(backObj->tempOwner != ai->playerID)
  461. return make_shared<Goals::CGoal>(Goals::GetObj(m->o->id.getNum()));
  462. return make_shared<Goals::CGoal>(setobjid(m->o->id.getNum()).setisElementar(true));
  463. }
  464. }
  465. return make_shared<Goals::CGoal>(Goals::Invalid()); //FIXME: unused?
  466. }
  467. TSubgoal GatherTroops::whatToDoToAchieve()
  468. {
  469. std::vector<const CGDwelling *> dwellings;
  470. for(const CGTownInstance *t : cb->getTownsInfo())
  471. {
  472. auto creature = VLC->creh->creatures[objid];
  473. if (t->subID == creature->faction) //TODO: how to force AI to build unupgraded creatures? :O
  474. {
  475. auto creatures = vstd::tryAt(t->town->creatures, creature->level - 1);
  476. if(!creatures)
  477. continue;
  478. int upgradeNumber = vstd::find_pos(*creatures, creature->idNumber);
  479. if(upgradeNumber < 0)
  480. continue;
  481. BuildingID bid(BuildingID::DWELL_FIRST + creature->level - 1 + upgradeNumber * GameConstants::CREATURES_PER_TOWN);
  482. if (t->hasBuilt(bid)) //this assumes only creatures with dwellings are assigned to faction
  483. {
  484. dwellings.push_back(t);
  485. }
  486. else
  487. {
  488. return make_shared<Goals::CGoal>(Goals::BuildThis().settown(t).setbid(bid));
  489. }
  490. }
  491. }
  492. for (auto obj : ai->visitableObjs)
  493. {
  494. if (obj->ID != Obj::CREATURE_GENERATOR1) //TODO: what with other creature generators?
  495. continue;
  496. auto d = dynamic_cast<const CGDwelling *>(obj);
  497. for (auto creature : d->creatures)
  498. {
  499. if (creature.first) //there are more than 0 creatures avaliabe
  500. {
  501. for (auto type : creature.second)
  502. {
  503. if (type == objid && ai->freeResources().canAfford(VLC->creh->creatures[type]->cost))
  504. dwellings.push_back(d);
  505. }
  506. }
  507. }
  508. }
  509. if (dwellings.size())
  510. {
  511. boost::sort(dwellings, isCloser);
  512. return make_shared<Goals::CGoal>(Goals::GetObj(dwellings.front()->id.getNum()));
  513. }
  514. else
  515. return make_shared<Goals::CGoal>(Goals::Explore());
  516. //TODO: exchange troops between heroes
  517. }
  518. TSubgoal Conquer::whatToDoToAchieve()
  519. {
  520. auto hs = cb->getHeroesInfo();
  521. int howManyHeroes = hs.size();
  522. erase(hs, [](const CGHeroInstance *h)
  523. {
  524. return contains(ai->lockedHeroes, h);
  525. });
  526. if(hs.empty()) //all heroes are busy. buy new one
  527. {
  528. if (howManyHeroes < 3 && ai->findTownWithTavern()) //we may want to recruit second hero. TODO: make it smart finally
  529. return make_shared<Goals::CGoal>(Goals::RecruitHero());
  530. else //find mobile hero with weakest army
  531. {
  532. hs = cb->getHeroesInfo();
  533. erase_if(hs, [](const CGHeroInstance *h)
  534. {
  535. return !h->movement; //only hero with movement are of interest for us
  536. });
  537. if (hs.empty())
  538. {
  539. if (howManyHeroes < GameConstants::MAX_HEROES_PER_PLAYER)
  540. return make_shared<Goals::CGoal>(Goals::RecruitHero());
  541. else
  542. throw cannotFulfillGoalException("No heroes with remaining MPs for exploring!\n");
  543. }
  544. boost::sort(hs, compareHeroStrength);
  545. }
  546. }
  547. const CGHeroInstance *h = hs.back();
  548. cb->setSelection(h);
  549. std::vector<const CGObjectInstance *> objs; //here we'll gather enemy towns and heroes
  550. ai->retreiveVisitableObjs(objs);
  551. erase_if(objs, [&](const CGObjectInstance *obj)
  552. {
  553. return (obj->ID != Obj::TOWN && obj->ID != Obj::HERO) //not town/hero
  554. || cb->getPlayerRelations(ai->playerID, obj->tempOwner) != PlayerRelations::ENEMIES;
  555. });
  556. if (objs.empty()) //experiment - try to conquer dwellings and mines, it should pay off
  557. {
  558. ai->retreiveVisitableObjs(objs);
  559. erase_if(objs, [&](const CGObjectInstance *obj)
  560. {
  561. return (obj->ID != Obj::CREATURE_GENERATOR1 && obj->ID != Obj::MINE) //not dwelling or mine
  562. || cb->getPlayerRelations(ai->playerID, obj->tempOwner) != PlayerRelations::ENEMIES;
  563. });
  564. }
  565. if(objs.empty())
  566. return make_shared<Goals::CGoal>(Goals::Explore()); //we need to find an enemy
  567. erase_if(objs, [&](const CGObjectInstance *obj)
  568. {
  569. return !isSafeToVisit(h, obj->visitablePos()) || vstd::contains (ai->reservedObjs, obj); //no need to capture same object twice
  570. });
  571. if(objs.empty())
  572. I_AM_ELEMENTAR;
  573. boost::sort(objs, isCloser);
  574. for(const CGObjectInstance *obj : objs)
  575. {
  576. if (ai->isAccessibleForHero(obj->visitablePos(), h))
  577. {
  578. ai->reserveObject(h, obj); //no one else will capture same object until we fail
  579. if (obj->ID == Obj::HERO)
  580. return make_shared<Goals::CGoal>(
  581. Goals::VisitHero().sethero(h).setobjid(obj->id.getNum()).setisAbstract(true));
  582. //track enemy hero
  583. else
  584. return make_shared<Goals::CGoal>(Goals::VisitTile(obj->visitablePos()).sethero(h));
  585. }
  586. }
  587. return make_shared<Goals::CGoal>(Goals::Explore()); //enemy is inaccessible
  588. }
  589. TSubgoal Build::whatToDoToAchieve()
  590. {
  591. I_AM_ELEMENTAR;
  592. }
  593. TSubgoal Invalid::whatToDoToAchieve()
  594. {
  595. I_AM_ELEMENTAR;
  596. }
  597. TSubgoal GatherArmy::whatToDoToAchieve()
  598. {
  599. //TODO: find hero if none set
  600. assert(hero);
  601. cb->setSelection(*hero);
  602. auto compareReinforcements = [this](const CGTownInstance *lhs, const CGTownInstance *rhs) -> bool
  603. {
  604. return howManyReinforcementsCanGet(hero, lhs) < howManyReinforcementsCanGet(hero, rhs);
  605. };
  606. std::vector<const CGTownInstance *> townsReachable;
  607. for(const CGTownInstance *t : cb->getTownsInfo())
  608. {
  609. if(!t->visitingHero && howManyReinforcementsCanGet(hero,t))
  610. {
  611. if(isReachable(t) && !vstd::contains (ai->townVisitsThisWeek[hero], t))
  612. townsReachable.push_back(t);
  613. }
  614. }
  615. if(townsReachable.size()) //try towns first
  616. {
  617. boost::sort(townsReachable, compareReinforcements);
  618. return make_shared<Goals::CGoal>(
  619. Goals::VisitTile(townsReachable.back()->visitablePos()).sethero(hero));
  620. }
  621. else
  622. {
  623. if (hero == ai->primaryHero()) //we can get army from other heroes
  624. {
  625. auto otherHeroes = cb->getHeroesInfo();
  626. auto heroDummy = hero;
  627. erase_if(otherHeroes, [heroDummy](const CGHeroInstance * h)
  628. {
  629. return (h == heroDummy.h || !ai->isAccessibleForHero(heroDummy->visitablePos(), h, true) || !ai->canGetArmy(heroDummy.h, h));
  630. });
  631. if (otherHeroes.size())
  632. {
  633. boost::sort(otherHeroes, compareArmyStrength); //TODO: check if hero has at least one stack more powerful than ours? not likely to fail
  634. int primaryPath, secondaryPath;
  635. auto h = otherHeroes.back();
  636. cb->setSelection(hero.h);
  637. primaryPath = cb->getPathInfo(h->visitablePos())->turns;
  638. cb->setSelection(h);
  639. secondaryPath = cb->getPathInfo(hero->visitablePos())->turns;
  640. if (primaryPath < secondaryPath)
  641. return make_shared<Goals::CGoal>(
  642. Goals::VisitHero().setisAbstract(true).setobjid(h->id.getNum()).sethero(hero));
  643. //go to the other hero if we are faster
  644. else
  645. return make_shared<Goals::CGoal>(
  646. Goals::VisitHero().setisAbstract(true).setobjid(hero->id.getNum()).sethero(h))
  647. ; //let the other hero come to us
  648. }
  649. }
  650. std::vector<const CGObjectInstance *> objs; //here we'll gather all dwellings
  651. ai->retreiveVisitableObjs(objs, true);
  652. erase_if(objs, [&](const CGObjectInstance *obj)
  653. {
  654. if(obj->ID != Obj::CREATURE_GENERATOR1)
  655. return true;
  656. auto relationToOwner = cb->getPlayerRelations(obj->getOwner(), ai->playerID);
  657. if(relationToOwner == PlayerRelations::ALLIES)
  658. return true;
  659. //Use flagged dwellings only when there are available creatures that we can afford
  660. if(relationToOwner == PlayerRelations::SAME_PLAYER)
  661. {
  662. auto dwelling = dynamic_cast<const CGDwelling*>(obj);
  663. for(auto & creLevel : dwelling->creatures)
  664. {
  665. if(creLevel.first)
  666. {
  667. for(auto & creatureID : creLevel.second)
  668. {
  669. auto creature = VLC->creh->creatures[creatureID];
  670. if(ai->freeResources().canAfford(creature->cost))
  671. return false;
  672. }
  673. }
  674. }
  675. }
  676. return true;
  677. });
  678. if(objs.empty()) //no possible objects, we did eveyrthing already
  679. return make_shared<Goals::CGoal>(Goals::Explore().sethero(hero));
  680. //TODO: check if we can recruit any creatures there, evaluate army
  681. else
  682. {
  683. boost::sort(objs, isCloser);
  684. HeroPtr h = nullptr;
  685. for(const CGObjectInstance *obj : objs)
  686. { //find safe dwelling
  687. auto pos = obj->visitablePos();
  688. if (shouldVisit (hero, obj)) //creatures fit in army
  689. h = hero;
  690. else
  691. {
  692. for(auto ourHero : cb->getHeroesInfo()) //make use of multiple heroes
  693. {
  694. if (shouldVisit(ourHero, obj))
  695. h = ourHero;
  696. }
  697. }
  698. if (h && isSafeToVisit(h, pos) && ai->isAccessibleForHero(pos, h))
  699. return make_shared<Goals::CGoal>(Goals::VisitTile(pos).sethero(h));
  700. }
  701. }
  702. }
  703. return make_shared<Goals::CGoal>(Goals::Explore().sethero(hero)); //find dwelling. use current hero to prevent him from doing nothing.
  704. }
  705. TSubgoal CGoal::whatToDoToAchieve()
  706. {
  707. logAi->debugStream() << boost::format("Decomposing goal of type %s") % name();
  708. return make_shared<Goals::CGoal>(Goals::Explore());
  709. }
  710. TSubgoal CGoal::goVisitOrLookFor(const CGObjectInstance *obj)
  711. {
  712. if(obj)
  713. return make_shared<Goals::CGoal>(Goals::GetObj(obj->id.getNum()));
  714. else
  715. return make_shared<Goals::CGoal>(Goals::Explore());
  716. }
  717. TSubgoal CGoal::lookForArtSmart(int aid)
  718. {
  719. return make_shared<Goals::CGoal>(Goals::Invalid());
  720. }
  721. bool CGoal::invalid() const
  722. {
  723. return goalType == INVALID;
  724. }