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