Goals.cpp 25 KB

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