Goals.cpp 25 KB

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