Goals.cpp 26 KB

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