Goals.cpp 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108
  1. #include "StdInc.h"
  2. #include "Goals.h"
  3. #include "VCAI.h"
  4. #include "Fuzzy.h"
  5. #include "../../lib/mapping/CMap.h" //for victory conditions
  6. /*
  7. * Goals.cpp, part of VCMI engine
  8. *
  9. * Authors: listed in file AUTHORS in main folder
  10. *
  11. * License: GNU General Public License v2.0 or later
  12. * Full text of license available in license.txt file, in main folder
  13. *
  14. */
  15. extern boost::thread_specific_ptr<CCallback> cb;
  16. extern boost::thread_specific_ptr<VCAI> ai;
  17. extern FuzzyHelper * fh; //TODO: this logic should be moved inside VCAI
  18. using namespace vstd;
  19. using namespace Goals;
  20. TSubgoal Goals::sptr(const AbstractGoal & tmp)
  21. {
  22. shared_ptr<AbstractGoal> ptr;
  23. ptr.reset(tmp.clone());
  24. return ptr;
  25. }
  26. std::string Goals::AbstractGoal::name() const //TODO: virtualize
  27. {
  28. std::string desc;
  29. switch (goalType)
  30. {
  31. case INVALID:
  32. return "INVALID";
  33. case WIN:
  34. return "WIN";
  35. case DO_NOT_LOSE:
  36. return "DO NOT LOOSE";
  37. case CONQUER:
  38. return "CONQUER";
  39. case BUILD:
  40. return "BUILD";
  41. case EXPLORE:
  42. desc = "EXPLORE";
  43. break;
  44. case GATHER_ARMY:
  45. desc = "GATHER ARMY";
  46. break;
  47. case BOOST_HERO:
  48. desc = "BOOST_HERO (unsupported)";
  49. break;
  50. case RECRUIT_HERO:
  51. return "RECRUIT HERO";
  52. case BUILD_STRUCTURE:
  53. return "BUILD STRUCTURE";
  54. case COLLECT_RES:
  55. desc = "COLLECT RESOURCE";
  56. break;
  57. case GATHER_TROOPS:
  58. desc = "GATHER TROOPS";
  59. break;
  60. case GET_OBJ:
  61. {
  62. auto obj = cb->getObjInstance(ObjectInstanceID(objid));
  63. if (obj)
  64. desc = "GET OBJ " + obj->getObjectName();
  65. }
  66. case FIND_OBJ:
  67. desc = "FIND OBJ " + boost::lexical_cast<std::string>(objid);
  68. break;
  69. case VISIT_HERO:
  70. {
  71. auto obj = cb->getObjInstance(ObjectInstanceID(objid));
  72. if (obj)
  73. desc = "VISIT HERO " + obj->getObjectName();
  74. }
  75. break;
  76. case GET_ART_TYPE:
  77. desc = "GET ARTIFACT OF TYPE " + VLC->arth->artifacts[aid]->Name();
  78. break;
  79. case ISSUE_COMMAND:
  80. return "ISSUE COMMAND (unsupported)";
  81. case VISIT_TILE:
  82. desc = "VISIT TILE " + tile();
  83. break;
  84. case CLEAR_WAY_TO:
  85. desc = "CLEAR WAY TO " + tile();
  86. break;
  87. case DIG_AT_TILE:
  88. desc = "DIG AT TILE " + tile();
  89. break;
  90. default:
  91. return boost::lexical_cast<std::string>(goalType);
  92. }
  93. if (hero.get(true)) //FIXME: used to crash when we lost hero and failed goal
  94. desc += " (" + hero->name + ")";
  95. return desc;
  96. }
  97. //TODO: virtualize if code gets complex?
  98. bool Goals::AbstractGoal::operator== (AbstractGoal &g)
  99. {
  100. if (g.goalType != goalType)
  101. return false;
  102. if (g.isElementar != isElementar) //elementar goals fulfill long term non-elementar goals (VisitTile)
  103. return false;
  104. switch (goalType)
  105. {
  106. //no parameters
  107. case INVALID:
  108. case WIN:
  109. case DO_NOT_LOSE:
  110. case RECRUIT_HERO: //recruit any hero, as yet
  111. return true;
  112. break;
  113. //assigned to hero, no parameters
  114. case CONQUER:
  115. case EXPLORE:
  116. case GATHER_ARMY: //actual value is indifferent
  117. case BOOST_HERO:
  118. return g.hero.h == hero.h; //how comes HeroPtrs are equal for different heroes?
  119. break;
  120. //assigned hero and tile
  121. case VISIT_TILE:
  122. case CLEAR_WAY_TO:
  123. return (g.hero.h == hero.h && g.tile == tile);
  124. break;
  125. //assigned hero and object
  126. case GET_OBJ:
  127. case FIND_OBJ: //TODO: use subtype?
  128. case VISIT_HERO:
  129. case GET_ART_TYPE:
  130. case DIG_AT_TILE:
  131. return (g.hero.h == hero.h && g.objid == objid);
  132. break;
  133. //no check atm
  134. case COLLECT_RES:
  135. case GATHER_TROOPS:
  136. case ISSUE_COMMAND:
  137. case BUILD: //TODO: should be decomposed to build specific structures
  138. case BUILD_STRUCTURE:
  139. default:
  140. return false;
  141. }
  142. }
  143. //TODO: find out why the following are not generated automatically on MVS?
  144. namespace Goals
  145. {
  146. template <>
  147. void CGoal<Win>::accept (VCAI * ai)
  148. {
  149. ai->tryRealize(static_cast<Win&>(*this));
  150. }
  151. template <>
  152. void CGoal<Build>::accept (VCAI * ai)
  153. {
  154. ai->tryRealize(static_cast<Build&>(*this));
  155. }
  156. template <>
  157. float CGoal<Win>::accept (FuzzyHelper * f)
  158. {
  159. return f->evaluate(static_cast<Win&>(*this));
  160. }
  161. template <>
  162. float CGoal<Build>::accept (FuzzyHelper * f)
  163. {
  164. return f->evaluate(static_cast<Build&>(*this));
  165. }
  166. }
  167. //TSubgoal AbstractGoal::whatToDoToAchieve()
  168. //{
  169. // logAi->debugStream() << boost::format("Decomposing goal of type %s") % name();
  170. // return sptr (Goals::Explore());
  171. //}
  172. TSubgoal Win::whatToDoToAchieve()
  173. {
  174. auto toBool = [=](const EventCondition &)
  175. {
  176. // TODO: proper implementation
  177. // Right now even already fulfilled goals will be included into generated list
  178. // Proper check should test if event condition is already fulfilled
  179. // Easiest way to do this is to call CGameState::checkForVictory but this function should not be
  180. // used on client side or in AI code
  181. return false;
  182. };
  183. std::vector<EventCondition> goals;
  184. for (const TriggeredEvent & event : cb->getMapHeader()->triggeredEvents)
  185. {
  186. //TODO: try to eliminate human player(s) using loss conditions that have isHuman element
  187. if (event.effect.type == EventEffect::VICTORY)
  188. {
  189. boost::range::copy(event.trigger.getFulfillmentCandidates(toBool), std::back_inserter(goals));
  190. }
  191. }
  192. //TODO: instead of returning first encountered goal AI should generate list of possible subgoals
  193. for (const EventCondition & goal : goals)
  194. {
  195. switch(goal.condition)
  196. {
  197. case EventCondition::HAVE_ARTIFACT:
  198. return sptr (Goals::GetArtOfType(goal.objectType));
  199. case EventCondition::DESTROY:
  200. {
  201. if (goal.object)
  202. {
  203. return sptr (Goals::GetObj(goal.object->id.getNum()));
  204. }
  205. else
  206. {
  207. // TODO: destroy all objects of type goal.objectType
  208. // This situation represents "kill all creatures" condition from H3
  209. break;
  210. }
  211. }
  212. case EventCondition::HAVE_BUILDING:
  213. {
  214. // TODO build other buildings apart from Grail
  215. // goal.objectType = buidingID to build
  216. // goal.object = optional, town in which building should be built
  217. // Represents "Improve town" condition from H3 (but unlike H3 it consists from 2 separate conditions)
  218. if (goal.objectType == BuildingID::GRAIL)
  219. {
  220. if(auto h = ai->getHeroWithGrail())
  221. {
  222. //hero is in a town that can host Grail
  223. if(h->visitedTown && !vstd::contains(h->visitedTown->forbiddenBuildings, BuildingID::GRAIL))
  224. {
  225. const CGTownInstance *t = h->visitedTown;
  226. return sptr (Goals::BuildThis(BuildingID::GRAIL, t));
  227. }
  228. else
  229. {
  230. auto towns = cb->getTownsInfo();
  231. towns.erase(boost::remove_if(towns,
  232. [](const CGTownInstance *t) -> bool
  233. {
  234. return vstd::contains(t->forbiddenBuildings, BuildingID::GRAIL);
  235. }),
  236. towns.end());
  237. boost::sort(towns, CDistanceSorter(h.get()));
  238. if(towns.size())
  239. {
  240. return sptr (Goals::VisitTile(towns.front()->visitablePos()).sethero(h));
  241. }
  242. }
  243. }
  244. double ratio = 0;
  245. // maybe make this check a bit more complex? For example:
  246. // 0.75 -> dig randomly within 3 tiles radius
  247. // 0.85 -> radius now 2 tiles
  248. // 0.95 -> 1 tile radius, position is fully known
  249. // AFAIK H3 AI does something like this
  250. int3 grailPos = cb->getGrailPos(ratio);
  251. if(ratio > 0.99)
  252. {
  253. return sptr (Goals::DigAtTile(grailPos));
  254. } //TODO: use FIND_OBJ
  255. else if(const CGObjectInstance * obj = ai->getUnvisitedObj(objWithID<Obj::OBELISK>)) //there are unvisited Obelisks
  256. return sptr (Goals::GetObj(obj->id.getNum()));
  257. else
  258. return sptr (Goals::Explore());
  259. }
  260. break;
  261. }
  262. case EventCondition::CONTROL:
  263. {
  264. if (goal.object)
  265. {
  266. return sptr (Goals::GetObj(goal.object->id.getNum()));
  267. }
  268. else
  269. {
  270. //TODO: control all objects of type "goal.objectType"
  271. // Represents H3 condition "Flag all mines"
  272. break;
  273. }
  274. }
  275. case EventCondition::HAVE_RESOURCES:
  276. //TODO mines? piles? marketplace?
  277. //save?
  278. return sptr (Goals::CollectRes(static_cast<Res::ERes>(goal.objectType), goal.value));
  279. case EventCondition::HAVE_CREATURES:
  280. return sptr (Goals::GatherTroops(goal.objectType, goal.value));
  281. case EventCondition::TRANSPORT:
  282. {
  283. //TODO. merge with bring Grail to town? So AI will first dig grail, then transport it using this goal and builds it
  284. // Represents "transport artifact" condition:
  285. // goal.objectType = type of artifact
  286. // goal.object = destination-town where artifact should be transported
  287. break;
  288. }
  289. case EventCondition::STANDARD_WIN:
  290. return sptr (Goals::Conquer());
  291. // Conditions that likely don't need any implementation
  292. case EventCondition::DAYS_PASSED:
  293. break; // goal.value = number of days for condition to trigger
  294. case EventCondition::DAYS_WITHOUT_TOWN:
  295. break; // goal.value = number of days to trigger this
  296. case EventCondition::IS_HUMAN:
  297. break; // Should be only used in calculation of candidates (see toBool lambda)
  298. case EventCondition::CONST_VALUE:
  299. break;
  300. default:
  301. assert(0);
  302. }
  303. }
  304. return sptr (Goals::Invalid());
  305. }
  306. TSubgoal FindObj::whatToDoToAchieve()
  307. {
  308. const CGObjectInstance * o = nullptr;
  309. if (resID > -1) //specified
  310. {
  311. for(const CGObjectInstance *obj : ai->visitableObjs)
  312. {
  313. if(obj->ID == objid && obj->subID == resID)
  314. {
  315. o = obj;
  316. break; //TODO: consider multiple objects and choose best
  317. }
  318. }
  319. }
  320. else
  321. {
  322. for(const CGObjectInstance *obj : ai->visitableObjs)
  323. {
  324. if(obj->ID == objid)
  325. {
  326. o = obj;
  327. break; //TODO: consider multiple objects and choose best
  328. }
  329. }
  330. }
  331. if (o && ai->isAccessible(o->pos)) //we don't use isAccessibleForHero as we don't know which hero it is
  332. return sptr (Goals::GetObj(o->id.getNum()));
  333. else
  334. return sptr (Goals::Explore());
  335. }
  336. std::string GetObj::completeMessage() const
  337. {
  338. return "hero " + hero.get()->name + " captured Object ID = " + boost::lexical_cast<std::string>(objid);
  339. }
  340. TSubgoal GetObj::whatToDoToAchieve()
  341. {
  342. const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(objid));
  343. if(!obj)
  344. return sptr (Goals::Explore());
  345. if (obj->tempOwner == ai->playerID) //we can't capture our own object -> move to Win codition
  346. throw cannotFulfillGoalException("Cannot capture my own object " + obj->getObjectName());
  347. int3 pos = obj->visitablePos();
  348. if (hero)
  349. {
  350. if (ai->isAccessibleForHero(pos, hero))
  351. return sptr (Goals::VisitTile(pos).sethero(hero));
  352. }
  353. else
  354. {
  355. for (auto h : cb->getHeroesInfo())
  356. {
  357. if (ai->isAccessibleForHero(pos, h))
  358. return sptr(Goals::VisitTile(pos).sethero(h)); //we must visit object with same hero, if any
  359. }
  360. }
  361. return sptr (Goals::ClearWayTo(pos).sethero(hero));
  362. }
  363. bool GetObj::fulfillsMe (TSubgoal goal)
  364. {
  365. if (goal->goalType == Goals::VISIT_TILE)
  366. {
  367. auto obj = cb->getObj(ObjectInstanceID(objid));
  368. if (obj && obj->visitablePos() == goal->tile) //object could be removed
  369. return true;
  370. }
  371. return false;
  372. }
  373. std::string VisitHero::completeMessage() const
  374. {
  375. return "hero " + hero.get()->name + " visited hero " + boost::lexical_cast<std::string>(objid);
  376. }
  377. TSubgoal VisitHero::whatToDoToAchieve()
  378. {
  379. const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(objid));
  380. if(!obj)
  381. return sptr (Goals::Explore());
  382. int3 pos = obj->visitablePos();
  383. if (hero && ai->isAccessibleForHero(pos, hero, true) && isSafeToVisit(hero, pos)) //enemy heroes can get reinforcements
  384. {
  385. if (hero->pos == pos)
  386. logAi->errorStream() << "Hero " << hero.name << " tries to visit himself.";
  387. else
  388. {
  389. //can't use VISIT_TILE here as tile appears blocked by target hero
  390. //FIXME: elementar goal should not be abstract
  391. return sptr (Goals::VisitHero(objid).sethero(hero).settile(pos).setisElementar(true));
  392. }
  393. }
  394. return sptr (Goals::Invalid());
  395. }
  396. bool VisitHero::fulfillsMe (TSubgoal goal)
  397. {
  398. if (goal->goalType == Goals::VISIT_TILE && cb->getObj(ObjectInstanceID(objid))->visitablePos() == goal->tile)
  399. return true;
  400. else
  401. return false;
  402. }
  403. TSubgoal GetArtOfType::whatToDoToAchieve()
  404. {
  405. TSubgoal alternativeWay = CGoal::lookForArtSmart(aid); //TODO: use
  406. if(alternativeWay->invalid())
  407. return sptr (Goals::FindObj(Obj::ARTIFACT, aid));
  408. return sptr (Goals::Invalid());
  409. }
  410. TSubgoal ClearWayTo::whatToDoToAchieve()
  411. {
  412. assert(cb->isInTheMap(tile)); //set tile
  413. if(!cb->isVisible(tile))
  414. {
  415. logAi->errorStream() << "Clear way should be used with visible tiles!";
  416. return sptr (Goals::Explore());
  417. }
  418. return (fh->chooseSolution(getAllPossibleSubgoals()));
  419. }
  420. TGoalVec ClearWayTo::getAllPossibleSubgoals()
  421. {
  422. TGoalVec ret;
  423. std::vector<const CGHeroInstance *> heroes;
  424. if (hero)
  425. heroes.push_back(hero.h);
  426. else
  427. {
  428. heroes = cb->getHeroesInfo();
  429. }
  430. for (auto h : heroes)
  431. {
  432. //TODO: handle clearing way to allied heroes that are blocked
  433. //if ((hero && hero->visitablePos() == tile && hero == *h) || //we can't free the way ourselves
  434. // h->visitablePos() == tile) //we are already on that tile! what does it mean?
  435. // continue;
  436. //if our hero is trapped, make sure we request clearing the way from OUR perspective
  437. SectorMap sm(h);
  438. int3 tileToHit = sm.firstTileToGet(h, tile);
  439. if (!tileToHit.valid())
  440. continue;
  441. if (isBlockedBorderGate(tileToHit))
  442. { //FIXME: this way we'll not visit gate and activate quest :?
  443. ret.push_back (sptr (Goals::FindObj (Obj::KEYMASTER, cb->getTile(tileToHit)->visitableObjects.back()->subID)));
  444. }
  445. auto topObj = cb->getTopObj(tileToHit);
  446. if (topObj)
  447. {
  448. if (vstd::contains(ai->reservedObjs, topObj) && !vstd::contains(ai->reservedHeroesMap[h], topObj))
  449. {
  450. throw goalFulfilledException (sptr(Goals::ClearWayTo(tile, h)));
  451. continue; //do not capure object reserved by other hero
  452. }
  453. if (topObj->ID == Obj::HERO && cb->getPlayerRelations(h->tempOwner, topObj->tempOwner) != PlayerRelations::ENEMIES)
  454. if (topObj != hero.get(true)) //the hero we want to free
  455. logAi->errorStream() << boost::format("%s stands in the way of %s") % topObj->getObjectName() % h->getObjectName();
  456. if (topObj->ID == Obj::QUEST_GUARD || topObj->ID == Obj::BORDERGUARD)
  457. {
  458. if (shouldVisit(h, topObj))
  459. {
  460. //do NOT use VISIT_TILE, as tile with quets guard can't be visited
  461. ret.push_back (sptr (Goals::GetObj(topObj->id.getNum()).sethero(h)));
  462. continue; //do not try to visit tile or gather army
  463. }
  464. else
  465. {
  466. //TODO: we should be able to return apriopriate quest here (VCAI::striveToQuest)
  467. logAi->debugStream() << "Quest guard blocks the way to " + tile();
  468. }
  469. }
  470. }
  471. if (isSafeToVisit(h, tileToHit)) //this makes sense only if tile is guarded, but there i no quest object
  472. {
  473. ret.push_back (sptr (Goals::VisitTile(tileToHit).sethero(h)));
  474. }
  475. else
  476. {
  477. ret.push_back (sptr (Goals::GatherArmy(evaluateDanger(tileToHit, h)*SAFE_ATTACK_CONSTANT).
  478. sethero(h).setisAbstract(true)));
  479. }
  480. }
  481. if (ai->canRecruitAnyHero())
  482. ret.push_back (sptr (Goals::RecruitHero()));
  483. if (ret.empty())
  484. {
  485. logAi->warnStream() << "There is no known way to clear the way to tile " + tile();
  486. throw goalFulfilledException (sptr(Goals::ClearWayTo(tile))); //make sure asigned hero gets unlocked
  487. }
  488. return ret;
  489. }
  490. std::string Explore::completeMessage() const
  491. {
  492. return "Hero " + hero.get()->name + " completed exploration";
  493. }
  494. TSubgoal Explore::whatToDoToAchieve()
  495. {
  496. auto ret = fh->chooseSolution(getAllPossibleSubgoals());
  497. if (hero) //use best step for this hero
  498. return ret;
  499. else
  500. {
  501. if (ret->hero.get(true))
  502. return sptr (sethero(ret->hero.h).setisAbstract(true)); //choose this hero and then continue with him
  503. else
  504. return ret; //other solutions, like buying hero from tavern
  505. }
  506. }
  507. TGoalVec Explore::getAllPossibleSubgoals()
  508. {
  509. TGoalVec ret;
  510. std::vector<const CGHeroInstance *> heroes;
  511. if (hero)
  512. heroes.push_back(hero.h);
  513. else
  514. {
  515. //heroes = ai->getUnblockedHeroes();
  516. heroes = cb->getHeroesInfo();
  517. erase_if (heroes, [](const HeroPtr h)
  518. {
  519. if (ai->getGoal(h)->goalType == Goals::EXPLORE) //do not reassign hero who is already explorer
  520. return true;
  521. if (!ai->isAbleToExplore(h))
  522. return true;
  523. return !h->movement; //saves time, immobile heroes are useless anyway
  524. });
  525. }
  526. //try to use buildings that uncover map
  527. std::vector<const CGObjectInstance *> objs;
  528. for (auto obj : ai->visitableObjs)
  529. {
  530. if (!vstd::contains(ai->alreadyVisited, obj))
  531. {
  532. switch (obj->ID.num)
  533. {
  534. case Obj::REDWOOD_OBSERVATORY:
  535. case Obj::PILLAR_OF_FIRE:
  536. case Obj::CARTOGRAPHER:
  537. case Obj::SUBTERRANEAN_GATE: //TODO: check ai->knownSubterraneanGates
  538. objs.push_back (obj);
  539. }
  540. }
  541. }
  542. for (auto h : heroes)
  543. {
  544. SectorMap sm(h);
  545. for (auto obj : objs) //double loop, performance risk?
  546. {
  547. auto t = sm.firstTileToGet(h, obj->visitablePos()); //we assume that no more than one tile on the way is guarded
  548. if (ai->canReachTile(h, t))
  549. ret.push_back (sptr(Goals::ClearWayTo(obj->visitablePos(), h).setisAbstract(true)));
  550. }
  551. int3 t = whereToExplore(h);
  552. if (t.valid())
  553. {
  554. ret.push_back (sptr (Goals::VisitTile(t).sethero(h)));
  555. }
  556. else
  557. {
  558. ai->markHeroUnableToExplore (h); //there is no freely accessible tile, do not poll this hero anymore
  559. //possible issues when gathering army to break
  560. if (hero.h == h || (!hero && h == ai->primaryHero().h)) //check this only ONCE, high cost
  561. {
  562. t = ai->explorationDesperate(h);
  563. if (t.valid()) //don't waste time if we are completely blocked
  564. ret.push_back (sptr(Goals::ClearWayTo(t, h).setisAbstract(true)));
  565. }
  566. }
  567. }
  568. //we either don't have hero yet or none of heroes can explore
  569. if ((!hero || ret.empty()) && ai->canRecruitAnyHero())
  570. ret.push_back (sptr(Goals::RecruitHero()));
  571. if (ret.empty())
  572. {
  573. throw goalFulfilledException (sptr(Goals::Explore().sethero(hero)));
  574. }
  575. //throw cannotFulfillGoalException("Cannot explore - no possible ways found!");
  576. return ret;
  577. }
  578. bool Explore::fulfillsMe (TSubgoal goal)
  579. {
  580. if (goal->goalType == Goals::EXPLORE)
  581. {
  582. if (goal->hero)
  583. return hero == goal->hero;
  584. else
  585. return true; //cancel ALL exploration
  586. }
  587. return false;
  588. }
  589. TSubgoal RecruitHero::whatToDoToAchieve()
  590. {
  591. const CGTownInstance *t = ai->findTownWithTavern();
  592. if(!t)
  593. return sptr (Goals::BuildThis(BuildingID::TAVERN));
  594. if(cb->getResourceAmount(Res::GOLD) < HERO_GOLD_COST)
  595. return sptr (Goals::CollectRes(Res::GOLD, HERO_GOLD_COST));
  596. return iAmElementar();
  597. }
  598. std::string VisitTile::completeMessage() const
  599. {
  600. return "Hero " + hero.get()->name + " visited tile " + tile();
  601. }
  602. TSubgoal VisitTile::whatToDoToAchieve()
  603. {
  604. auto ret = fh->chooseSolution(getAllPossibleSubgoals());
  605. if (ret->hero)
  606. {
  607. if (isSafeToVisit(ret->hero, tile) && ai->isAccessibleForHero(tile, ret->hero))
  608. {
  609. ret->setisElementar(true);
  610. return ret;
  611. }
  612. else
  613. {
  614. return sptr (Goals::GatherArmy(evaluateDanger(tile, *ret->hero) * SAFE_ATTACK_CONSTANT)
  615. .sethero(ret->hero).setisAbstract(true));
  616. }
  617. }
  618. return ret;
  619. }
  620. TGoalVec VisitTile::getAllPossibleSubgoals()
  621. {
  622. assert(cb->isInTheMap(tile));
  623. TGoalVec ret;
  624. if (!cb->isVisible(tile))
  625. ret.push_back (sptr(Goals::Explore())); //what sense does it make?
  626. else
  627. {
  628. std::vector<const CGHeroInstance *> heroes;
  629. if (hero)
  630. heroes.push_back(hero.h); //use assigned hero if any
  631. else
  632. heroes = cb->getHeroesInfo(); //use most convenient hero
  633. for (auto h : heroes)
  634. {
  635. if (ai->isAccessibleForHero(tile, h))
  636. ret.push_back (sptr(Goals::VisitTile(tile).sethero(h)));
  637. }
  638. if (ai->canRecruitAnyHero())
  639. ret.push_back (sptr(Goals::RecruitHero()));
  640. }
  641. if (ret.empty())
  642. {
  643. auto obj = frontOrNull(cb->getVisitableObjs(tile));
  644. if (obj && obj->ID == Obj::HERO && obj->tempOwner == ai->playerID) //our own hero stands on that tile
  645. {
  646. if (hero.get(true) && hero->id == obj->id) //if it's assigned hero, visit tile. If it's different hero, we can't visit tile now
  647. ret.push_back(sptr(Goals::VisitTile(tile).sethero(dynamic_cast<const CGHeroInstance *>(obj)).setisElementar(true)));
  648. else
  649. throw cannotFulfillGoalException("Tile is already occupied by another hero "); //FIXME: we should give up this tile earlier
  650. }
  651. else
  652. ret.push_back (sptr(Goals::ClearWayTo(tile)));
  653. }
  654. //important - at least one sub-goal must handle case which is impossible to fulfill (unreachable tile)
  655. return ret;
  656. }
  657. TSubgoal DigAtTile::whatToDoToAchieve()
  658. {
  659. const CGObjectInstance *firstObj = frontOrNull(cb->getVisitableObjs(tile));
  660. if(firstObj && firstObj->ID == Obj::HERO && firstObj->tempOwner == ai->playerID) //we have hero at dest
  661. {
  662. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(firstObj);
  663. sethero(h).setisElementar(true);
  664. return sptr (*this);
  665. }
  666. return sptr (Goals::VisitTile(tile));
  667. }
  668. TSubgoal BuildThis::whatToDoToAchieve()
  669. {
  670. //TODO check res
  671. //look for town
  672. //prerequisites?
  673. return iAmElementar();
  674. }
  675. TSubgoal CollectRes::whatToDoToAchieve()
  676. {
  677. std::vector<const IMarket*> markets;
  678. std::vector<const CGObjectInstance*> visObjs;
  679. ai->retreiveVisitableObjs(visObjs, true);
  680. for(const CGObjectInstance *obj : visObjs)
  681. {
  682. if(const IMarket *m = IMarket::castFrom(obj, false))
  683. {
  684. if(obj->ID == Obj::TOWN && obj->tempOwner == ai->playerID && m->allowsTrade(EMarketMode::RESOURCE_RESOURCE))
  685. markets.push_back(m);
  686. else if(obj->ID == Obj::TRADING_POST) //TODO a moze po prostu test na pozwalanie handlu?
  687. markets.push_back(m);
  688. }
  689. }
  690. boost::sort(markets, [](const IMarket *m1, const IMarket *m2) -> bool
  691. {
  692. return m1->getMarketEfficiency() < m2->getMarketEfficiency();
  693. });
  694. markets.erase(boost::remove_if(markets, [](const IMarket *market) -> bool
  695. {
  696. return !(market->o->ID == Obj::TOWN && market->o->tempOwner == ai->playerID)
  697. && !ai->isAccessible(market->o->visitablePos());
  698. }),markets.end());
  699. if(!markets.size())
  700. {
  701. for(const CGTownInstance *t : cb->getTownsInfo())
  702. {
  703. if(cb->canBuildStructure(t, BuildingID::MARKETPLACE) == EBuildingState::ALLOWED)
  704. return sptr (Goals::BuildThis(BuildingID::MARKETPLACE, t));
  705. }
  706. }
  707. else
  708. {
  709. const IMarket *m = markets.back();
  710. //attempt trade at back (best prices)
  711. int howManyCanWeBuy = 0;
  712. for(Res::ERes i = Res::WOOD; i <= Res::GOLD; vstd::advance(i, 1))
  713. {
  714. if(i == resID) continue;
  715. int toGive = -1, toReceive = -1;
  716. m->getOffer(i, resID, toGive, toReceive, EMarketMode::RESOURCE_RESOURCE);
  717. assert(toGive > 0 && toReceive > 0);
  718. howManyCanWeBuy += toReceive * (cb->getResourceAmount(i) / toGive);
  719. }
  720. if(howManyCanWeBuy + cb->getResourceAmount(static_cast<Res::ERes>(resID)) >= value)
  721. {
  722. auto backObj = cb->getTopObj(m->o->visitablePos()); //it'll be a hero if we have one there; otherwise marketplace
  723. assert(backObj);
  724. if (backObj->tempOwner != ai->playerID)
  725. {
  726. return sptr (Goals::GetObj(m->o->id.getNum()));
  727. }
  728. else
  729. {
  730. return sptr (Goals::GetObj(m->o->id.getNum()).setisElementar(true));
  731. }
  732. }
  733. }
  734. return sptr (setisElementar(true)); //all the conditions for trade are met
  735. }
  736. TSubgoal GatherTroops::whatToDoToAchieve()
  737. {
  738. std::vector<const CGDwelling *> dwellings;
  739. for(const CGTownInstance *t : cb->getTownsInfo())
  740. {
  741. auto creature = VLC->creh->creatures[objid];
  742. if (t->subID == creature->faction) //TODO: how to force AI to build unupgraded creatures? :O
  743. {
  744. auto creatures = vstd::tryAt(t->town->creatures, creature->level - 1);
  745. if(!creatures)
  746. continue;
  747. int upgradeNumber = vstd::find_pos(*creatures, creature->idNumber);
  748. if(upgradeNumber < 0)
  749. continue;
  750. BuildingID bid(BuildingID::DWELL_FIRST + creature->level - 1 + upgradeNumber * GameConstants::CREATURES_PER_TOWN);
  751. if (t->hasBuilt(bid)) //this assumes only creatures with dwellings are assigned to faction
  752. {
  753. dwellings.push_back(t);
  754. }
  755. else
  756. {
  757. return sptr (Goals::BuildThis(bid, t));
  758. }
  759. }
  760. }
  761. for (auto obj : ai->visitableObjs)
  762. {
  763. if (obj->ID != Obj::CREATURE_GENERATOR1) //TODO: what with other creature generators?
  764. continue;
  765. auto d = dynamic_cast<const CGDwelling *>(obj);
  766. for (auto creature : d->creatures)
  767. {
  768. if (creature.first) //there are more than 0 creatures avaliabe
  769. {
  770. for (auto type : creature.second)
  771. {
  772. if (type == objid && ai->freeResources().canAfford(VLC->creh->creatures[type]->cost))
  773. dwellings.push_back(d);
  774. }
  775. }
  776. }
  777. }
  778. if (dwellings.size())
  779. {
  780. typedef std::map<const CGHeroInstance *, const CGDwelling *> TDwellMap;
  781. // sorted helper
  782. auto comparator = [](const TDwellMap::value_type & a, const TDwellMap::value_type & b) -> bool
  783. {
  784. const CGPathNode *ln = ai->myCb->getPathsInfo(a.first)->getPathInfo(a.second->visitablePos()),
  785. *rn = ai->myCb->getPathsInfo(b.first)->getPathInfo(b.second->visitablePos());
  786. if(ln->turns != rn->turns)
  787. return ln->turns < rn->turns;
  788. return (ln->moveRemains > rn->moveRemains);
  789. };
  790. // for all owned heroes generate map <hero -> nearest dwelling>
  791. TDwellMap nearestDwellings;
  792. for (const CGHeroInstance * hero : cb->getHeroesInfo(true))
  793. {
  794. nearestDwellings[hero] = *boost::range::min_element(dwellings, CDistanceSorter(hero));
  795. }
  796. // find hero who is nearest to a dwelling
  797. const CGDwelling * nearest = boost::range::min_element(nearestDwellings, comparator)->second;
  798. return sptr (Goals::GetObj(nearest->id.getNum()));
  799. }
  800. else
  801. return sptr (Goals::Explore());
  802. //TODO: exchange troops between heroes
  803. }
  804. TSubgoal Conquer::whatToDoToAchieve()
  805. {
  806. return fh->chooseSolution (getAllPossibleSubgoals());
  807. }
  808. TGoalVec Conquer::getAllPossibleSubgoals()
  809. {
  810. TGoalVec ret;
  811. auto conquerable = [](const CGObjectInstance * obj) -> bool
  812. {
  813. if (cb->getPlayerRelations(ai->playerID, obj->tempOwner) == PlayerRelations::ENEMIES)
  814. {
  815. switch (obj->ID.num)
  816. {
  817. case Obj::TOWN:
  818. case Obj::HERO:
  819. case Obj::CREATURE_GENERATOR1:
  820. case Obj::MINE: //TODO: check ai->knownSubterraneanGates
  821. return true;
  822. }
  823. }
  824. return false;
  825. };
  826. std::vector<const CGObjectInstance *> objs;
  827. for (auto obj : ai->visitableObjs)
  828. {
  829. if (conquerable(obj))
  830. objs.push_back (obj);
  831. }
  832. for (auto h : cb->getHeroesInfo())
  833. {
  834. SectorMap sm(h);
  835. std::vector<const CGObjectInstance *> ourObjs(objs); //copy common objects
  836. for (auto obj : ai->reservedHeroesMap[h]) //add objects reserved by this hero
  837. {
  838. if (conquerable(obj))
  839. ourObjs.push_back(obj);
  840. }
  841. for (auto obj : ourObjs) //double loop, performance risk?
  842. {
  843. auto t = sm.firstTileToGet(h, obj->visitablePos()); //we assume that no more than one tile on the way is guarded
  844. if (ai->canReachTile(h, t))
  845. ret.push_back (sptr(Goals::ClearWayTo(obj->visitablePos(), h).setisAbstract(true)));
  846. }
  847. }
  848. if (!objs.empty() && ai->canRecruitAnyHero()) //probably no point to recruit hero if we see no objects to capture
  849. ret.push_back (sptr(Goals::RecruitHero()));
  850. if (ret.empty())
  851. ret.push_back (sptr(Goals::Explore())); //we need to find an enemy
  852. return ret;
  853. }
  854. TSubgoal Build::whatToDoToAchieve()
  855. {
  856. return iAmElementar();
  857. }
  858. TSubgoal Invalid::whatToDoToAchieve()
  859. {
  860. return iAmElementar();
  861. }
  862. std::string GatherArmy::completeMessage() const
  863. {
  864. return "Hero " + hero.get()->name + " gathered army of value " + boost::lexical_cast<std::string>(value);
  865. }
  866. TSubgoal GatherArmy::whatToDoToAchieve()
  867. {
  868. //TODO: find hero if none set
  869. assert(hero.h);
  870. return fh->chooseSolution (getAllPossibleSubgoals()); //find dwelling. use current hero to prevent him from doing nothing.
  871. }
  872. TGoalVec GatherArmy::getAllPossibleSubgoals()
  873. {
  874. //get all possible towns, heroes and dwellings we may use
  875. TGoalVec ret;
  876. //TODO: include evaluation of monsters gather in calculation
  877. for (auto t : cb->getTownsInfo())
  878. {
  879. auto pos = t->visitablePos();
  880. if (ai->isAccessibleForHero(pos, hero))
  881. {
  882. if(!t->visitingHero && howManyReinforcementsCanGet(hero,t))
  883. {
  884. if (!vstd::contains (ai->townVisitsThisWeek[hero], t))
  885. ret.push_back (sptr (Goals::VisitTile(pos).sethero(hero)));
  886. }
  887. auto bid = ai->canBuildAnyStructure(t, std::vector<BuildingID>
  888. (unitsSource, unitsSource + ARRAY_COUNT(unitsSource)), 8 - cb->getDate(Date::DAY_OF_WEEK));
  889. if (bid != BuildingID::NONE)
  890. ret.push_back (sptr(BuildThis(bid, t)));
  891. }
  892. }
  893. auto otherHeroes = cb->getHeroesInfo();
  894. auto heroDummy = hero;
  895. erase_if(otherHeroes, [heroDummy](const CGHeroInstance * h)
  896. {
  897. return (h == heroDummy.h || !ai->isAccessibleForHero(heroDummy->visitablePos(), h, true)
  898. || !ai->canGetArmy(heroDummy.h, h) || ai->getGoal(h)->goalType == Goals::GATHER_ARMY);
  899. });
  900. for (auto h : otherHeroes)
  901. {
  902. ret.push_back (sptr (Goals::VisitHero(h->id.getNum()).setisAbstract(true).sethero(hero)));
  903. //go to the other hero if we are faster
  904. ret.push_back (sptr (Goals::VisitHero(hero->id.getNum()).setisAbstract(true).sethero(h)));
  905. //let the other hero come to us
  906. }
  907. std::vector <const CGObjectInstance *> objs;
  908. for (auto obj : ai->visitableObjs)
  909. {
  910. if(obj->ID == Obj::CREATURE_GENERATOR1)
  911. {
  912. auto relationToOwner = cb->getPlayerRelations(obj->getOwner(), ai->playerID);
  913. //Use flagged dwellings only when there are available creatures that we can afford
  914. if(relationToOwner == PlayerRelations::SAME_PLAYER)
  915. {
  916. auto dwelling = dynamic_cast<const CGDwelling*>(obj);
  917. for(auto & creLevel : dwelling->creatures)
  918. {
  919. if(creLevel.first)
  920. {
  921. for(auto & creatureID : creLevel.second)
  922. {
  923. auto creature = VLC->creh->creatures[creatureID];
  924. if (ai->freeResources().canAfford(creature->cost))
  925. objs.push_back(obj);
  926. }
  927. }
  928. }
  929. }
  930. }
  931. }
  932. for(auto h : cb->getHeroesInfo())
  933. {
  934. for (auto obj : objs)
  935. { //find safe dwelling
  936. auto pos = obj->visitablePos();
  937. if (ai->isGoodForVisit(obj, h))
  938. ret.push_back (sptr (Goals::VisitTile(pos).sethero(h)));
  939. }
  940. }
  941. if (ai->canRecruitAnyHero()) //this is not stupid in early phase of game
  942. ret.push_back (sptr(Goals::RecruitHero()));
  943. if (ret.empty())
  944. {
  945. if (hero == ai->primaryHero() || value >= 1.1f)
  946. ret.push_back (sptr(Goals::Explore()));
  947. else //workaround to break loop - seemingly there are no ways to explore left
  948. throw goalFulfilledException (sptr(Goals::GatherArmy(0).sethero(hero)));
  949. }
  950. return ret;
  951. }
  952. //TSubgoal AbstractGoal::whatToDoToAchieve()
  953. //{
  954. // logAi->debugStream() << boost::format("Decomposing goal of type %s") % name();
  955. // return sptr (Goals::Explore());
  956. //}
  957. TSubgoal AbstractGoal::goVisitOrLookFor(const CGObjectInstance *obj)
  958. {
  959. if(obj)
  960. return sptr (Goals::GetObj(obj->id.getNum()));
  961. else
  962. return sptr (Goals::Explore());
  963. }
  964. TSubgoal AbstractGoal::lookForArtSmart(int aid)
  965. {
  966. return sptr (Goals::Invalid());
  967. }
  968. bool AbstractGoal::invalid() const
  969. {
  970. return goalType == INVALID;
  971. }
  972. void AbstractGoal::accept (VCAI * ai)
  973. {
  974. ai->tryRealize(*this);
  975. }
  976. template<typename T>
  977. void CGoal<T>::accept (VCAI * ai)
  978. {
  979. ai->tryRealize(static_cast<T&>(*this)); //casting enforces template instantiation
  980. }
  981. float AbstractGoal::accept (FuzzyHelper * f)
  982. {
  983. return f->evaluate(*this);
  984. }
  985. template<typename T>
  986. float CGoal<T>::accept (FuzzyHelper * f)
  987. {
  988. return f->evaluate(static_cast<T&>(*this)); //casting enforces template instantiation
  989. }