Goals.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  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. std::string GetObj::completeMessage() const
  190. {
  191. return "hero " + hero.get()->name + " captured Object ID = " + boost::lexical_cast<std::string>(objid);
  192. }
  193. TSubgoal GetObj::whatToDoToAchieve()
  194. {
  195. const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(objid));
  196. if(!obj)
  197. return sptr (Goals::Explore());
  198. int3 pos = obj->visitablePos();
  199. return sptr (Goals::VisitTile(pos));
  200. }
  201. std::string VisitHero::completeMessage() const
  202. {
  203. return "hero " + hero.get()->name + " visited hero " + boost::lexical_cast<std::string>(objid);
  204. }
  205. TSubgoal VisitHero::whatToDoToAchieve()
  206. {
  207. const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(objid));
  208. if(!obj)
  209. return sptr (Goals::Explore());
  210. int3 pos = obj->visitablePos();
  211. if (hero && ai->isAccessibleForHero(pos, hero, true) && isSafeToVisit(hero, pos)) //enemy heroes can get reinforcements
  212. {
  213. assert (hero->pos != pos); //don't try to visit yourself
  214. settile(pos).setisElementar(true);
  215. return sptr (*this);
  216. }
  217. return sptr (Goals::Invalid());
  218. }
  219. TSubgoal GetArtOfType::whatToDoToAchieve()
  220. {
  221. TSubgoal alternativeWay = CGoal::lookForArtSmart(aid); //TODO: use
  222. if(alternativeWay->invalid())
  223. return sptr (Goals::FindObj(Obj::ARTIFACT, aid));
  224. return sptr (Goals::Invalid());
  225. }
  226. TSubgoal ClearWayTo::whatToDoToAchieve()
  227. {
  228. assert(tile.x >= 0); //set tile
  229. if(!cb->isVisible(tile))
  230. {
  231. logAi->errorStream() << "Clear way should be used with visible tiles!";
  232. return sptr (Goals::Explore());
  233. }
  234. HeroPtr h = hero ? hero : ai->primaryHero();
  235. if(!h)
  236. return sptr (Goals::RecruitHero());
  237. cb->setSelection(*h);
  238. SectorMap sm;
  239. bool dropToFile = false;
  240. if(dropToFile) //for debug purposes
  241. sm.write("test.txt");
  242. int3 tileToHit = sm.firstTileToGet(h, tile);
  243. //if(isSafeToVisit(h, tileToHit))
  244. if(isBlockedBorderGate(tileToHit))
  245. { //FIXME: this way we'll not visit gate and activate quest :?
  246. return sptr (Goals::FindObj (Obj::KEYMASTER, cb->getTile(tileToHit)->visitableObjects.back()->subID));
  247. }
  248. //FIXME: this code shouldn't be necessary
  249. if(tileToHit == tile)
  250. {
  251. logAi->errorStream() << boost::format("Very strange, tile to hit is %s and tile is also %s, while hero %s is at %s\n")
  252. % tileToHit % tile % h->name % h->visitablePos();
  253. throw cannotFulfillGoalException("Retrieving first tile to hit failed (probably)!");
  254. }
  255. auto topObj = backOrNull(cb->getVisitableObjs(tileToHit));
  256. if(topObj && topObj->ID == Obj::HERO && cb->getPlayerRelations(h->tempOwner, topObj->tempOwner) != PlayerRelations::ENEMIES)
  257. {
  258. std::string problem = boost::str(boost::format("%s stands in the way of %s.\n") % topObj->getHoverText() % h->getHoverText());
  259. throw cannotFulfillGoalException(problem);
  260. }
  261. return sptr (Goals::VisitTile(tileToHit).sethero(h));
  262. //FIXME:: attempts to visit completely unreachable tile with hero results in stall
  263. //TODO czy istnieje lepsza droga?
  264. throw cannotFulfillGoalException("Cannot reach given tile!"); //how and when could this be used?
  265. }
  266. std::string Explore::completeMessage() const
  267. {
  268. return "Hero " + hero.get()->name + " completed exploration";
  269. };
  270. TSubgoal Explore::whatToDoToAchieve()
  271. {
  272. auto objs = ai->visitableObjs; //try to use buildings that uncover map
  273. erase_if(objs, [&](const CGObjectInstance *obj) -> bool
  274. {
  275. if (vstd::contains(ai->alreadyVisited, obj))
  276. return true;
  277. switch (obj->ID.num)
  278. {
  279. case Obj::REDWOOD_OBSERVATORY:
  280. case Obj::PILLAR_OF_FIRE:
  281. case Obj::CARTOGRAPHER:
  282. case Obj::SUBTERRANEAN_GATE: //TODO: check ai->knownSubterraneanGates
  283. //case Obj::MONOLITH1:
  284. //case obj::MONOLITH2:
  285. //case obj::MONOLITH3:
  286. //case Obj::WHIRLPOOL:
  287. return false; //do not erase
  288. break;
  289. default:
  290. return true;
  291. }
  292. });
  293. if (objs.size())
  294. {
  295. if (hero.get(true))
  296. {
  297. for (auto obj : objs)
  298. {
  299. auto pos = obj->visitablePos();
  300. //FIXME: this confition fails if everything but guarded subterranen gate was explored. in this case we should gather army for hero
  301. if (isSafeToVisit(hero, pos) && ai->isAccessibleForHero(pos, hero))
  302. return sptr (Goals::VisitTile(pos).sethero(hero));
  303. }
  304. }
  305. else
  306. {
  307. for (auto obj : objs)
  308. {
  309. auto pos = obj->visitablePos();
  310. if (ai->isAccessible (pos)) //TODO: check safety?
  311. return sptr (Goals::VisitTile(pos).sethero(hero));
  312. }
  313. }
  314. }
  315. if (hero)
  316. {
  317. int3 t = whereToExplore(hero);
  318. if (t.z == -1) //no safe tile to explore - we need to break!
  319. {
  320. erase_if (objs, [&](const CGObjectInstance *obj) -> bool
  321. {
  322. switch (obj->ID.num)
  323. {
  324. case Obj::CARTOGRAPHER:
  325. case Obj::SUBTERRANEAN_GATE:
  326. //case Obj::MONOLITH1:
  327. //case obj::MONOLITH2:
  328. //case obj::MONOLITH3:
  329. //case Obj::WHIRLPOOL:
  330. return false; //do not erase
  331. break;
  332. default:
  333. return true;
  334. }
  335. });
  336. if (objs.size())
  337. {
  338. return sptr (Goals::VisitTile(objs.front()->visitablePos()).sethero(hero).setisAbstract(true));
  339. }
  340. else
  341. throw cannotFulfillGoalException("Cannot explore - no possible ways found!");
  342. }
  343. return sptr (Goals::VisitTile(t).sethero(hero));
  344. }
  345. auto hs = cb->getHeroesInfo();
  346. int howManyHeroes = hs.size();
  347. erase(hs, [](const CGHeroInstance *h)
  348. {
  349. return contains(ai->lockedHeroes, h);
  350. });
  351. if(hs.empty()) //all heroes are busy. buy new one
  352. {
  353. if (howManyHeroes < 3 && ai->findTownWithTavern()) //we may want to recruit second hero. TODO: make it smart finally
  354. return sptr (Goals::RecruitHero());
  355. else //find mobile hero with weakest army
  356. {
  357. hs = cb->getHeroesInfo();
  358. erase_if(hs, [](const CGHeroInstance *h)
  359. {
  360. return !h->movement; //only hero with movement are of interest for us
  361. });
  362. if (hs.empty())
  363. {
  364. if (howManyHeroes < GameConstants::MAX_HEROES_PER_PLAYER)
  365. return sptr (Goals::RecruitHero());
  366. else
  367. throw cannotFulfillGoalException("No heroes with remaining MPs for exploring!\n");
  368. }
  369. boost::sort(hs, compareMovement); //closer to what?
  370. }
  371. }
  372. const CGHeroInstance *h = hs.front();
  373. return sptr (sethero(h).setisAbstract(true));
  374. return iAmElementar(); //FIXME: how can this be called?
  375. };
  376. TSubgoal RecruitHero::whatToDoToAchieve()
  377. {
  378. const CGTownInstance *t = ai->findTownWithTavern();
  379. if(!t)
  380. return sptr (Goals::BuildThis(BuildingID::TAVERN));
  381. if(cb->getResourceAmount(Res::GOLD) < HERO_GOLD_COST)
  382. return sptr (Goals::CollectRes(Res::GOLD, HERO_GOLD_COST));
  383. return iAmElementar();
  384. }
  385. std::string VisitTile::completeMessage() const
  386. {
  387. return "Hero " + hero.get()->name + " visited tile " + tile();
  388. }
  389. TSubgoal VisitTile::whatToDoToAchieve()
  390. {
  391. if(!cb->isVisible(tile))
  392. return sptr (Goals::Explore());
  393. if(hero && !ai->isAccessibleForHero(tile, hero))
  394. hero = nullptr;
  395. if(!hero)
  396. {
  397. if(cb->getHeroesInfo().empty())
  398. {
  399. return sptr (Goals::RecruitHero());
  400. }
  401. for(const CGHeroInstance *h : cb->getHeroesInfo())
  402. {
  403. if(ai->isAccessibleForHero(tile, h))
  404. {
  405. hero = h;
  406. break;
  407. }
  408. }
  409. }
  410. if(hero)
  411. {
  412. if(isSafeToVisit(hero, tile))
  413. return sptr (setisElementar(true));
  414. else
  415. {
  416. return sptr (Goals::GatherArmy(evaluateDanger(tile, *hero) * SAFE_ATTACK_CONSTANT).sethero(hero));
  417. }
  418. }
  419. else //inaccessible for all heroes
  420. {
  421. return sptr (Goals::ClearWayTo(tile));
  422. }
  423. }
  424. TSubgoal DigAtTile::whatToDoToAchieve()
  425. {
  426. const CGObjectInstance *firstObj = frontOrNull(cb->getVisitableObjs(tile));
  427. if(firstObj && firstObj->ID == Obj::HERO && firstObj->tempOwner == ai->playerID) //we have hero at dest
  428. {
  429. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(firstObj);
  430. sethero(h).setisElementar(true);
  431. return sptr (*this);
  432. }
  433. return sptr (Goals::VisitTile(tile));
  434. }
  435. TSubgoal BuildThis::whatToDoToAchieve()
  436. {
  437. //TODO check res
  438. //look for town
  439. //prerequisites?
  440. return iAmElementar();
  441. }
  442. TSubgoal CollectRes::whatToDoToAchieve()
  443. {
  444. std::vector<const IMarket*> markets;
  445. std::vector<const CGObjectInstance*> visObjs;
  446. ai->retreiveVisitableObjs(visObjs, true);
  447. for(const CGObjectInstance *obj : visObjs)
  448. {
  449. if(const IMarket *m = IMarket::castFrom(obj, false))
  450. {
  451. if(obj->ID == Obj::TOWN && obj->tempOwner == ai->playerID && m->allowsTrade(EMarketMode::RESOURCE_RESOURCE))
  452. markets.push_back(m);
  453. else if(obj->ID == Obj::TRADING_POST) //TODO a moze po prostu test na pozwalanie handlu?
  454. markets.push_back(m);
  455. }
  456. }
  457. boost::sort(markets, [](const IMarket *m1, const IMarket *m2) -> bool
  458. {
  459. return m1->getMarketEfficiency() < m2->getMarketEfficiency();
  460. });
  461. markets.erase(boost::remove_if(markets, [](const IMarket *market) -> bool
  462. {
  463. return !(market->o->ID == Obj::TOWN && market->o->tempOwner == ai->playerID)
  464. && !ai->isAccessible(market->o->visitablePos());
  465. }),markets.end());
  466. if(!markets.size())
  467. {
  468. for(const CGTownInstance *t : cb->getTownsInfo())
  469. {
  470. if(cb->canBuildStructure(t, BuildingID::MARKETPLACE) == EBuildingState::ALLOWED)
  471. return sptr (Goals::BuildThis(BuildingID::MARKETPLACE, t));
  472. }
  473. }
  474. else
  475. {
  476. const IMarket *m = markets.back();
  477. //attempt trade at back (best prices)
  478. int howManyCanWeBuy = 0;
  479. for(Res::ERes i = Res::WOOD; i <= Res::GOLD; vstd::advance(i, 1))
  480. {
  481. if(i == resID) continue;
  482. int toGive = -1, toReceive = -1;
  483. m->getOffer(i, resID, toGive, toReceive, EMarketMode::RESOURCE_RESOURCE);
  484. assert(toGive > 0 && toReceive > 0);
  485. howManyCanWeBuy += toReceive * (cb->getResourceAmount(i) / toGive);
  486. }
  487. if(howManyCanWeBuy + cb->getResourceAmount(static_cast<Res::ERes>(resID)) >= value)
  488. {
  489. auto backObj = backOrNull(cb->getVisitableObjs(m->o->visitablePos())); //it'll be a hero if we have one there; otherwise marketplace
  490. assert(backObj);
  491. if (backObj->tempOwner != ai->playerID)
  492. {
  493. return sptr (Goals::GetObj(m->o->id.getNum()));
  494. }
  495. else
  496. {
  497. return sptr (Goals::GetObj(m->o->id.getNum()).setisElementar(true));
  498. }
  499. }
  500. }
  501. return sptr (Goals::Invalid()); //FIXME: unused?
  502. }
  503. TSubgoal GatherTroops::whatToDoToAchieve()
  504. {
  505. std::vector<const CGDwelling *> dwellings;
  506. for(const CGTownInstance *t : cb->getTownsInfo())
  507. {
  508. auto creature = VLC->creh->creatures[objid];
  509. if (t->subID == creature->faction) //TODO: how to force AI to build unupgraded creatures? :O
  510. {
  511. auto creatures = vstd::tryAt(t->town->creatures, creature->level - 1);
  512. if(!creatures)
  513. continue;
  514. int upgradeNumber = vstd::find_pos(*creatures, creature->idNumber);
  515. if(upgradeNumber < 0)
  516. continue;
  517. BuildingID bid(BuildingID::DWELL_FIRST + creature->level - 1 + upgradeNumber * GameConstants::CREATURES_PER_TOWN);
  518. if (t->hasBuilt(bid)) //this assumes only creatures with dwellings are assigned to faction
  519. {
  520. dwellings.push_back(t);
  521. }
  522. else
  523. {
  524. return sptr (Goals::BuildThis(bid, t));
  525. }
  526. }
  527. }
  528. for (auto obj : ai->visitableObjs)
  529. {
  530. if (obj->ID != Obj::CREATURE_GENERATOR1) //TODO: what with other creature generators?
  531. continue;
  532. auto d = dynamic_cast<const CGDwelling *>(obj);
  533. for (auto creature : d->creatures)
  534. {
  535. if (creature.first) //there are more than 0 creatures avaliabe
  536. {
  537. for (auto type : creature.second)
  538. {
  539. if (type == objid && ai->freeResources().canAfford(VLC->creh->creatures[type]->cost))
  540. dwellings.push_back(d);
  541. }
  542. }
  543. }
  544. }
  545. if (dwellings.size())
  546. {
  547. boost::sort(dwellings, isCloser);
  548. return sptr (Goals::GetObj(dwellings.front()->id.getNum()));
  549. }
  550. else
  551. return sptr (Goals::Explore());
  552. //TODO: exchange troops between heroes
  553. }
  554. TSubgoal Conquer::whatToDoToAchieve()
  555. {
  556. auto hs = cb->getHeroesInfo();
  557. int howManyHeroes = hs.size();
  558. erase(hs, [](const CGHeroInstance *h)
  559. {
  560. return contains(ai->lockedHeroes, h);
  561. });
  562. if(hs.empty()) //all heroes are busy. buy new one
  563. {
  564. if (howManyHeroes < 3 && ai->findTownWithTavern()) //we may want to recruit second hero. TODO: make it smart finally
  565. return sptr (Goals::RecruitHero());
  566. else //find mobile hero with weakest army
  567. {
  568. hs = cb->getHeroesInfo();
  569. erase_if(hs, [](const CGHeroInstance *h)
  570. {
  571. return !h->movement; //only hero with movement are of interest for us
  572. });
  573. if (hs.empty())
  574. {
  575. if (howManyHeroes < GameConstants::MAX_HEROES_PER_PLAYER)
  576. return sptr (Goals::RecruitHero());
  577. else
  578. throw cannotFulfillGoalException("No heroes with remaining MPs for exploring!\n");
  579. }
  580. boost::sort(hs, compareHeroStrength);
  581. }
  582. }
  583. const CGHeroInstance *h = hs.back();
  584. cb->setSelection(h);
  585. std::vector<const CGObjectInstance *> objs; //here we'll gather enemy towns and heroes
  586. ai->retreiveVisitableObjs(objs);
  587. erase_if(objs, [&](const CGObjectInstance *obj)
  588. {
  589. return (obj->ID != Obj::TOWN && obj->ID != Obj::HERO) //not town/hero
  590. || cb->getPlayerRelations(ai->playerID, obj->tempOwner) != PlayerRelations::ENEMIES;
  591. });
  592. if (objs.empty()) //experiment - try to conquer dwellings and mines, it should pay off
  593. {
  594. ai->retreiveVisitableObjs(objs);
  595. erase_if(objs, [&](const CGObjectInstance *obj)
  596. {
  597. return (obj->ID != Obj::CREATURE_GENERATOR1 && obj->ID != Obj::MINE) //not dwelling or mine
  598. || cb->getPlayerRelations(ai->playerID, obj->tempOwner) != PlayerRelations::ENEMIES;
  599. });
  600. }
  601. if(objs.empty())
  602. return sptr (Goals::Explore()); //we need to find an enemy
  603. erase_if(objs, [&](const CGObjectInstance *obj)
  604. {
  605. return !isSafeToVisit(h, obj->visitablePos()) || vstd::contains (ai->reservedObjs, obj); //no need to capture same object twice
  606. });
  607. if(objs.empty())
  608. return iAmElementar();
  609. boost::sort(objs, isCloser);
  610. for(const CGObjectInstance *obj : objs)
  611. {
  612. if (ai->isAccessibleForHero(obj->visitablePos(), h))
  613. {
  614. ai->reserveObject(h, obj); //no one else will capture same object until we fail
  615. if (obj->ID == Obj::HERO)
  616. return sptr (Goals::VisitHero(obj->id.getNum()).sethero(h).setisAbstract(true));
  617. //track enemy hero
  618. else
  619. return sptr (Goals::VisitTile(obj->visitablePos()).sethero(h));
  620. }
  621. }
  622. return sptr (Goals::Explore()); //enemy is inaccessible
  623. }
  624. TSubgoal Build::whatToDoToAchieve()
  625. {
  626. return iAmElementar();
  627. }
  628. TSubgoal Invalid::whatToDoToAchieve()
  629. {
  630. return iAmElementar();
  631. }
  632. std::string GatherArmy::completeMessage() const
  633. {
  634. return "Hero " + hero.get()->name + " gathered army of value " + boost::lexical_cast<std::string>(value);
  635. };
  636. TSubgoal GatherArmy::whatToDoToAchieve()
  637. {
  638. //TODO: find hero if none set
  639. assert(hero);
  640. cb->setSelection(*hero);
  641. auto compareReinforcements = [this](const CGTownInstance *lhs, const CGTownInstance *rhs) -> bool
  642. {
  643. return howManyReinforcementsCanGet(hero, lhs) < howManyReinforcementsCanGet(hero, rhs);
  644. };
  645. std::vector<const CGTownInstance *> townsReachable;
  646. for(const CGTownInstance *t : cb->getTownsInfo())
  647. {
  648. if(!t->visitingHero && howManyReinforcementsCanGet(hero,t))
  649. {
  650. if(isReachable(t) && !vstd::contains (ai->townVisitsThisWeek[hero], t))
  651. townsReachable.push_back(t);
  652. }
  653. }
  654. if(townsReachable.size()) //try towns first
  655. {
  656. boost::sort(townsReachable, compareReinforcements);
  657. return sptr (Goals::VisitTile(townsReachable.back()->visitablePos()).sethero(hero));
  658. }
  659. else
  660. {
  661. if (hero == ai->primaryHero()) //we can get army from other heroes
  662. {
  663. auto otherHeroes = cb->getHeroesInfo();
  664. auto heroDummy = hero;
  665. erase_if(otherHeroes, [heroDummy](const CGHeroInstance * h)
  666. {
  667. return (h == heroDummy.h || !ai->isAccessibleForHero(heroDummy->visitablePos(), h, true) || !ai->canGetArmy(heroDummy.h, h));
  668. });
  669. if (otherHeroes.size())
  670. {
  671. boost::sort(otherHeroes, compareArmyStrength); //TODO: check if hero has at least one stack more powerful than ours? not likely to fail
  672. int primaryPath, secondaryPath;
  673. auto h = otherHeroes.back();
  674. cb->setSelection(hero.h);
  675. primaryPath = cb->getPathInfo(h->visitablePos())->turns;
  676. cb->setSelection(h);
  677. secondaryPath = cb->getPathInfo(hero->visitablePos())->turns;
  678. if (primaryPath < secondaryPath)
  679. return sptr (Goals::VisitHero(h->id.getNum()).setisAbstract(true).sethero(hero));
  680. //go to the other hero if we are faster
  681. else
  682. return sptr (Goals::VisitHero(hero->id.getNum()).setisAbstract(true).sethero(h));
  683. //let the other hero come to us
  684. }
  685. }
  686. std::vector<const CGObjectInstance *> objs; //here we'll gather all dwellings
  687. ai->retreiveVisitableObjs(objs, true);
  688. erase_if(objs, [&](const CGObjectInstance *obj)
  689. {
  690. if(obj->ID != Obj::CREATURE_GENERATOR1)
  691. return true;
  692. auto relationToOwner = cb->getPlayerRelations(obj->getOwner(), ai->playerID);
  693. if(relationToOwner == PlayerRelations::ALLIES)
  694. return true;
  695. //Use flagged dwellings only when there are available creatures that we can afford
  696. if(relationToOwner == PlayerRelations::SAME_PLAYER)
  697. {
  698. auto dwelling = dynamic_cast<const CGDwelling*>(obj);
  699. for(auto & creLevel : dwelling->creatures)
  700. {
  701. if(creLevel.first)
  702. {
  703. for(auto & creatureID : creLevel.second)
  704. {
  705. auto creature = VLC->creh->creatures[creatureID];
  706. if(ai->freeResources().canAfford(creature->cost))
  707. return false;
  708. }
  709. }
  710. }
  711. }
  712. return true;
  713. });
  714. if(objs.empty()) //no possible objects, we did eveyrthing already
  715. return sptr (Goals::Explore(hero));
  716. //TODO: check if we can recruit any creatures there, evaluate army
  717. else
  718. {
  719. boost::sort(objs, isCloser);
  720. HeroPtr h = nullptr;
  721. for(const CGObjectInstance *obj : objs)
  722. { //find safe dwelling
  723. auto pos = obj->visitablePos();
  724. if (shouldVisit (hero, obj)) //creatures fit in army
  725. h = hero;
  726. else
  727. {
  728. for(auto ourHero : cb->getHeroesInfo()) //make use of multiple heroes
  729. {
  730. if (shouldVisit(ourHero, obj))
  731. h = ourHero;
  732. }
  733. }
  734. if (h && isSafeToVisit(h, pos) && ai->isAccessibleForHero(pos, h))
  735. return sptr (Goals::VisitTile(pos).sethero(h));
  736. }
  737. }
  738. }
  739. return sptr (Goals::Explore(hero)); //find dwelling. use current hero to prevent him from doing nothing.
  740. }
  741. //TSubgoal AbstractGoal::whatToDoToAchieve()
  742. //{
  743. // logAi->debugStream() << boost::format("Decomposing goal of type %s") % name();
  744. // return sptr (Goals::Explore());
  745. //}
  746. TSubgoal AbstractGoal::goVisitOrLookFor(const CGObjectInstance *obj)
  747. {
  748. if(obj)
  749. return sptr (Goals::GetObj(obj->id.getNum()));
  750. else
  751. return sptr (Goals::Explore());
  752. }
  753. TSubgoal AbstractGoal::lookForArtSmart(int aid)
  754. {
  755. return sptr (Goals::Invalid());
  756. }
  757. bool AbstractGoal::invalid() const
  758. {
  759. return goalType == INVALID;
  760. }
  761. void AbstractGoal::accept (VCAI * ai)
  762. {
  763. ai->tryRealize(*this);
  764. };