Nullkiller.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. #include "StdInc.h"
  2. #include "Nullkiller.h"
  3. #include "../VCAI.h"
  4. #include "../AIHelper.h"
  5. #include "../Behaviors/CaptureObjectsBehavior.h"
  6. #include "../Behaviors/RecruitHeroBehavior.h"
  7. #include "../Goals/Invalid.h"
  8. extern boost::thread_specific_ptr<CCallback> cb;
  9. extern boost::thread_specific_ptr<VCAI> ai;
  10. Nullkiller::Nullkiller()
  11. {
  12. priorityEvaluator.reset(new PriorityEvaluator());
  13. }
  14. Goals::TSubgoal Nullkiller::choseBestTask(Goals::TGoalVec tasks)
  15. {
  16. Goals::TSubgoal bestTask = *vstd::maxElementByFun(tasks, [](Goals::TSubgoal goal) -> float
  17. {
  18. return goal->priority;
  19. });
  20. return bestTask;
  21. }
  22. Goals::TSubgoal Nullkiller::choseBestTask(Behavior & behavior)
  23. {
  24. logAi->debug("Checking behavior %s", behavior.toString());
  25. auto tasks = behavior.getTasks();
  26. if(tasks.empty())
  27. {
  28. logAi->debug("Behavior %s found no tasks", behavior.toString());
  29. return Goals::sptr(Goals::Invalid());
  30. }
  31. for(auto task : tasks)
  32. {
  33. task->setpriority(priorityEvaluator->evaluate(task));
  34. }
  35. auto task = choseBestTask(tasks);
  36. logAi->debug("Behavior %s returns %s(%s), priority %f", behavior.toString(), task->name(), task->tile.toString(), task->priority);
  37. return task;
  38. }
  39. void Nullkiller::resetAiState()
  40. {
  41. lockedHeroes.clear();
  42. }
  43. void Nullkiller::updateAiState()
  44. {
  45. auto activeHeroes = ai->getMyHeroes();
  46. vstd::erase_if(activeHeroes, [&](const HeroPtr & hero) -> bool{
  47. return vstd::contains(lockedHeroes, hero);
  48. });
  49. ai->ah->updatePaths(activeHeroes, true);
  50. }
  51. void Nullkiller::makeTurn()
  52. {
  53. resetAiState();
  54. while(true)
  55. {
  56. updateAiState();
  57. Goals::TGoalVec bestTasks = {
  58. choseBestTask(CaptureObjectsBehavior()),
  59. choseBestTask(RecruitHeroBehavior())
  60. };
  61. Goals::TSubgoal bestTask = choseBestTask(bestTasks);
  62. if(bestTask->invalid())
  63. {
  64. logAi->trace("No goals found. Ending turn.");
  65. return;
  66. }
  67. logAi->debug("Trying to realize %s (value %2.3f)", bestTask->name(), bestTask->priority);
  68. try
  69. {
  70. activeHero = bestTask->hero;
  71. bestTask->accept(ai.get());
  72. }
  73. catch(goalFulfilledException &)
  74. {
  75. logAi->trace(bestTask->completeMessage());
  76. }
  77. catch(std::exception & e)
  78. {
  79. logAi->debug("Failed to realize subgoal of type %s, I will stop.", bestTask->name());
  80. logAi->debug("The error message was: %s", e.what());
  81. return;
  82. }
  83. }
  84. }