Goals.cpp 25 KB

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