Goals.cpp 23 KB

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