The Battle for Wesnoth  1.15.2+dev
recruitment.cpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2013 - 2018 by Felix Bauer
3  Part of the Battle for Wesnoth Project https://www.wesnoth.org/
4 
5  This program is free software; you can redistribute it and/or modify
6  it under the terms of the GNU General Public License as published by
7  the Free Software Foundation; either version 2 of the License, or
8  (at your option) any later version.
9  This program is distributed in the hope that it will be useful,
10  but WITHOUT ANY WARRANTY.
11 
12  See the COPYING file for more details.
13  */
14 
15 /**
16  * @file
17  * Recruitment Engine by flix
18  * See https://wiki.wesnoth.org/AI_Recruitment
19  */
20 
22 
23 #include "ai/actions.hpp"
24 #include "ai/composite/rca.hpp"
25 #include "ai/manager.hpp"
26 #include "actions/attack.hpp"
27 #include "attack_prediction.hpp"
28 #include "display.hpp"
29 #include "filter_context.hpp"
30 #include "game_board.hpp"
31 #include "log.hpp"
32 #include "map/map.hpp"
33 #include "map/label.hpp"
34 #include "pathfind/pathfind.hpp"
35 #include "pathutils.hpp"
36 #include "random.hpp"
37 #include "resources.hpp"
38 #include "team.hpp"
39 #include "tod_manager.hpp"
40 #include "units/filter.hpp"
41 #include "units/map.hpp"
42 #include "units/types.hpp"
43 #include "units/unit.hpp"
44 #include "variable.hpp"
45 
46 #include <cmath>
47 
48 static lg::log_domain log_ai_recruitment("ai/recruitment");
49 #define LOG_AI_RECRUITMENT LOG_STREAM(info, log_ai_recruitment)
50 #define ERR_AI_RECRUITMENT LOG_STREAM(err, log_ai_recruitment)
51 
52 namespace ai {
53 
54 namespace default_recruitment {
55 
56 namespace {
57 /**
58  * CONSTANTS
59  */
60 
61 // This is used for a income estimation. We'll calculate the estimated income of this much
62 // future turns and decide if we'd gain gold if we start to recruit no units anymore.
63 const static int SAVE_GOLD_FORECAST_TURNS = 5;
64 
65 // When a team has less then this much units, consider recruit-list too.
66 const static unsigned int UNIT_THRESHOLD = 5;
67 
68 // Defines the shape of the border-zone between enemies.
69 // Higher values mean more important hexes.
70 const static double MAP_BORDER_THICKNESS = 2.0;
71 const static double MAP_BORDER_WIDTH = 0.2;
72 
73 // This parameter can be used to shift all important hexes in one directon.
74 // For example if our AI should act rather defensivly we may want to set
75 // this value to a negative number. Then the AI will more care about hexes
76 // nearer to the own units.
77 const static int MAP_OFFENSIVE_SHIFT = 0;
78 
79 // When villages are this near to imprtant hexes they count as important.
80 const static int MAP_VILLAGE_NEARNESS_THRESHOLD = 3;
81 
82 // Radius of area around important villages.
83 const static int MAP_VILLAGE_SURROUNDING = 1;
84 
85 // Determines the power of a raw unit comparison
86 // A higher power means that *very good* units will be
87 // stronger favored compared to just *good* units.
88 const static double COMBAT_SCORE_POWER = 1.;
89 
90 // A cache is used to store the simulation results.
91 // This value determines how much the average defenses of the important hexes can differ
92 // until the simulation will run again.
93 const static double COMBAT_CACHE_TOLERANCY = 0.5;
94 
95 // The old recruitment CA usually recruited too many scouts.
96 // To prevent this we multiply the aspect village_per_scout with this constant.
97 const static double VILLAGE_PER_SCOUT_MULTIPLICATOR = 2.;
98 }
99 
100 std::string data::to_string() const {
101  std::stringstream s;
102  s << "---------------Content of leader data---------------\n";
103  s << "For leader: " << leader->name() << "\n";
104  s << "ratio_score: " << ratio_score << "\n";
105  s << "recruit_count: " << recruit_count << "\n\n";
106  for (const score_map::value_type& entry : scores) {
107  s << std::setw(20) << entry.first <<
108  " score: " << std::setw(7) << entry.second << "\n";
109  }
110  s << "----------------------------------------------------\n";
111  return s.str();
112 }
113 
115  : candidate_action(context, cfg),
116  important_hexes_(),
117  important_terrain_(),
118  own_units_in_combat_counter_(0),
119  average_local_cost_(),
120  cheapest_unit_costs_(),
121  combat_cache_(),
122  recruit_situation_change_observer_(),
123  average_lawful_bonus_(0.0),
124  recruitment_instructions_(),
125  recruitment_instructions_turn_(-1),
126  own_units_count_(),
127  total_own_units_(0),
128  scouts_wanted_(0)
129 {
130  if (cfg["state"] == "save_gold") {
131  state_ = SAVE_GOLD;
132  } else if (cfg["state"] == "spend_all_gold") {
134  } else {
135  state_ = NORMAL;
136  }
137 }
138 
141  if (state_ == SAVE_GOLD) {
142  cfg["state"] = "save_gold";
143  } else if (state_ == SPEND_ALL_GOLD) {
144  cfg["state"] = "spend_all_gold";
145  } else {
146  cfg["state"] = "normal";
147  }
148  return cfg;
149 }
150 
152  // Check if the recruitment list has changed.
153  // Then cheapest_unit_costs_ is not valid anymore.
155  cheapest_unit_costs_.clear();
157  }
158 
159  // When evaluate() is called the first time this turn,
160  // we'll retrieve the recruitment-instruction aspect.
165  LOG_AI_RECRUITMENT << "Recruitment-instructions updated:\n";
167  }
168 
169  // Check if we have something to do.
170  const config* job = get_most_important_job();
171  if (!job) {
172  return BAD_SCORE;
173  }
174 
175  const unit_map& units = resources::gameboard->units();
176  const std::vector<unit_map::const_iterator> leaders = units.find_leaders(get_side());
177 
178  for (const unit_map::const_iterator& leader : leaders) {
179  // Need to check this here, otherwise recruiting might be blacklisted
180  // if no allowed leader is on a keep yet
181  if (!is_allowed_unit(*leader)) {
182  continue;
183  }
184 
185  if (leader == resources::gameboard->units().end()) {
186  return BAD_SCORE;
187  }
188  // Check Gold. But proceed if there is a unit with cost <= 0 (WML can do that)
189  int cheapest_unit_cost = get_cheapest_unit_cost_for_leader(leader);
190  if (current_team().gold() < cheapest_unit_cost && cheapest_unit_cost > 0) {
191  continue;
192  }
193 
194  const map_location& loc = leader->get_location();
195  if (resources::gameboard->map().is_keep(loc) &&
197  return get_score();
198  }
199  }
200 
201  return BAD_SCORE;
202 }
203 
205  LOG_AI_RECRUITMENT << "\n\n\n------------AI RECRUITMENT BEGIN---------------\n\n";
206  LOG_AI_RECRUITMENT << "TURN: " << resources::tod_manager->turn() <<
207  " SIDE: " << current_team().side() << "\n";
208 
209  /*
210  * Check which leaders can recruit and collect them in leader_data.
211  */
212 
213  const unit_map& units = resources::gameboard->units();
214  const gamemap& map = resources::gameboard->map();
215  const std::vector<unit_map::const_iterator> leaders = units.find_leaders(get_side());
216 
217  // This is the central datastructure with all score_tables in it.
218  std::vector<data> leader_data;
219 
220  std::set<std::string> global_recruits;
221 
222  for (const unit_map::const_iterator& leader : leaders) {
223  const map_location& keep = leader->get_location();
224  if (!is_allowed_unit(*leader)) {
225  LOG_AI_RECRUITMENT << "Leader " << leader->name() << " is not allowed recruiter. \n";
226  continue;
227  }
228  if (!resources::gameboard->map().is_keep(keep)) {
229  LOG_AI_RECRUITMENT << "Leader " << leader->name() << " is not on keep. \n";
230  continue;
231  }
233  LOG_AI_RECRUITMENT << "Leader " << leader->name() << " has no free hexes \n";
234  continue;
235  }
236  int cheapest_unit_cost = get_cheapest_unit_cost_for_leader(leader);
237  if (current_team().gold() < cheapest_unit_cost && cheapest_unit_cost > 0) {
238  LOG_AI_RECRUITMENT << "Leader " << leader->name() << " recruits are too expensive. \n";
239  continue;
240  }
241 
242  // Leader can recruit.
243 
244  data data(leader);
245 
246  // Add team recruits.
247  for (const std::string& recruit : current_team().recruits()) {
248  if (!unit_types.find(recruit)) {
249  lg::wml_error() << "Unit-type \"" << recruit << "\" doesn't exist.\n";
250  }
251  data.recruits.insert(recruit);
252  data.scores[recruit] = 0.0;
253  global_recruits.insert(recruit);
254  }
255 
256  // Add extra recruits.
257  for (const std::string& recruit : leader->recruits()) {
258  if (!unit_types.find(recruit)) {
259  lg::wml_error() << "Unit-type \"" << recruit << "\" doesn't exist.\n";
260  }
261  data.recruits.insert(recruit);
262  data.scores[recruit] = 0.0;
263  global_recruits.insert(recruit);
264  }
265 
266  // Add recalls.
267  // Recalls are treated as recruits. While recruiting
268  // we'll check if we can do a recall instead of a recruitment.
269  for (const unit_const_ptr & recall : current_team().recall_list()) {
270  // Check if this leader is allowed to recall this unit.
271  const unit_filter ufilt( vconfig(leader->recall_filter()));
272  if (!ufilt(*recall, map_location::null_location())) {
273  continue;
274  }
275  const double recall_value = recruitment::recall_unit_value(recall);
276  if (recall_value < 0) {
277  continue; // Unit is not worth to get recalled.
278  }
279  data.recruits.insert(recall->type_id());
280  data.scores[recall->type_id()] = 0.0;
281  global_recruits.insert(recall->type_id());
282  }
283 
284  // Check if leader is in danger. (If a enemies unit can attack the leader)
285  data.in_danger = power_projection(leader->get_location(), get_enemy_dstsrc()) > 0;
286 
287  // If yes, set ratio_score very high, so this leader will get priority while recruiting.
288  if (data.in_danger) {
289  data.ratio_score = 50;
291  LOG_AI_RECRUITMENT << "Leader " << leader->name() << " is in danger.\n";
292  }
293 
294  leader_data.push_back(data);
295  }
296 
297  if (leader_data.empty()) {
298  LOG_AI_RECRUITMENT << "No leader available for recruiting. \n";
299  return; // This CA is going to be blacklisted for this turn.
300  }
301 
302  if (global_recruits.empty()) {
303  LOG_AI_RECRUITMENT << "All leaders have empty recruitment lists. \n";
304  return; // This CA is going to be blacklisted for this turn.
305  }
306 
307  /**
308  * Find important hexes and calculate other static things.
309  */
310 
312  // Show "x" on important hexes if debug mode is activated AND
313  // the log domain "ai/recruitment" is used.
314  if (game_config::debug && !lg::info().dont_log(log_ai_recruitment)) {
316  }
317 
318  for (const map_location& hex : important_hexes_) {
319  ++important_terrain_[map[hex]];
320  }
321 
325 
326  /**
327  * Fill scores.
328  */
329 
330  do_combat_analysis(&leader_data);
331 
332  LOG_AI_RECRUITMENT << "Scores before extra treatments:\n";
333  for (const data& data : leader_data) {
334  LOG_AI_RECRUITMENT << "\n" << data.to_string();
335  }
336 
337  do_similarity_penalty(&leader_data);
338  do_randomness(&leader_data);
339  handle_recruitment_more(&leader_data);
340 
341  LOG_AI_RECRUITMENT << "Scores after extra treatments:\n";
342  for (const data& data : leader_data) {
343  LOG_AI_RECRUITMENT << "\n" << data.to_string();
344  }
345 
346  /**
347  * Do recruitment according to [recruit]-tags and scores.
348  * Note that the scores don't indicate the preferred mix to recruit but rather
349  * the preferred mix of all units. So already existing units are considered.
350  */
351 
353  config* job = nullptr;
354  do { // Recruitment loop
356 
357  // Check if we may want to save gold by not recruiting.
358  update_state();
359  int save_gold_turn = get_recruitment_save_gold()["active"].to_int(2); // From aspect.
360  int current_turn = resources::tod_manager->turn();
361  bool save_gold_active = save_gold_turn > 0 && save_gold_turn <= current_turn;
362  if (state_ == SAVE_GOLD && save_gold_active) {
363  break;
364  }
365 
366  job = get_most_important_job();
367  if (!job) {
368  LOG_AI_RECRUITMENT << "All recruitment jobs (recruitment_instructions) done.\n";
369  break;
370  }
371  LOG_AI_RECRUITMENT << "Executing this job:\n" << *job << "\n";
372 
373  data* best_leader_data = get_best_leader_from_ratio_scores(leader_data, job);
374  if (!best_leader_data) {
375  LOG_AI_RECRUITMENT << "Leader with job (recruitment_instruction) is not on keep.\n";
376  if (remove_job_if_no_blocker(job)) {
377  continue;
378  } else {
379  break;
380  }
381  }
382  LOG_AI_RECRUITMENT << "We want to have " << scouts_wanted_ << " more scouts.\n";
383 
384  const std::string best_recruit = get_best_recruit_from_scores(*best_leader_data, job);
385  if (best_recruit.empty()) {
386  LOG_AI_RECRUITMENT << "Cannot fulfill recruitment-instruction.\n";
387  if (remove_job_if_no_blocker(job)) {
388  continue;
389  } else {
390  break;
391  }
392  }
393 
394  LOG_AI_RECRUITMENT << "Best recruit is: " << best_recruit << "\n";
395  const std::string* recall_id = get_appropriate_recall(best_recruit, *best_leader_data);
396  if (recall_id) {
397  LOG_AI_RECRUITMENT << "Found appropriate recall with id: " << *recall_id << "\n";
398  action_result = execute_recall(*recall_id, *best_leader_data);
399  } else {
400  action_result = execute_recruit(best_recruit, *best_leader_data);
401  }
402 
403  if (action_result->is_ok()) {
404  ++own_units_count_[best_recruit];
406  if (recruit_matches_type(best_recruit, "scout")) {
407  --scouts_wanted_;
408  }
409 
410  // Update the current job.
411  if (!job->operator[]("total").to_bool(false)) {
412  job->operator[]("number") = job->operator[]("number").to_int(99999) - 1;
413  }
414 
415  // Check if something changed in the recruitment list (WML can do that).
416  // If yes, just return/break. evaluate() and execute() will be called again.
418  break;
419  }
420  // Check if the gamestate changed more than once.
421  // (Recruitment will trigger one gamestate change, WML could trigger more changes.)
422  // If yes, just return/break. evaluate() and execute() will be called again.
424  break;
425  }
426 
427  } else {
428  LOG_AI_RECRUITMENT << "Recruit result not ok.\n";
429  // We'll end up here if
430  // 1. We haven't enough gold,
431  // 2. There aren't any free hexes around leaders,
432  // 3. This leader can not recruit this type (this can happen after a recall)
433  }
434  } while((action_result && action_result->is_ok()) || !action_result);
435  // A action_result may be uninitialized if a job was removed. Continue then anyway.
436 
437  // Recruiting is done now.
438  // Update state_ for next execution().
439 
440  if (state_ == LEADER_IN_DANGER) {
441  state_ = NORMAL;
442  }
443 
444  int status = (action_result) ? action_result->get_status() : -1;
445  bool no_gold = (status == recruit_result::E_NO_GOLD || status == recall_result::E_NO_GOLD);
446  if (state_ == SPEND_ALL_GOLD && no_gold) {
447  state_ = SAVE_GOLD;
448  }
449  if (job && no_gold) {
451  }
452 }
453 
454 /**
455  * A helper function for execute().
456  */
457 action_result_ptr recruitment::execute_recall(const std::string& id, data& leader_data) {
459  recall_result = check_recall_action(id, map_location::null_location(),
460  leader_data.leader->get_location());
461  if (recall_result->is_ok()) {
462  recall_result->execute();
463  ++leader_data.recruit_count;
464  }
465  return recall_result;
466 }
467 
468 /**
469  * A helper function for execute().
470  */
471 action_result_ptr recruitment::execute_recruit(const std::string& type, data& leader_data) {
473  recruit_result = check_recruit_action(type, map_location::null_location(),
474  leader_data.leader->get_location());
475 
476  if (recruit_result->is_ok()) {
477  recruit_result->execute();
478  LOG_AI_RECRUITMENT << "Recruited " << type << "\n";
479  ++leader_data.recruit_count;
480  }
481  return recruit_result;
482 }
483 
484 /**
485  * A helper function for execute().
486  * Checks if this unit type can be recalled.
487  * If yes, we calculate a estimated value in gold of the recall unit.
488  * If this value is less then the recall cost, we dismiss the unit.
489  * The unit with the highest value will be returned.
490  */
491 
493  double average_cost_of_advanced_unit = 0;
494  int counter = 0;
495  for (const std::string& advancement : recall_unit->advances_to()) {
496  const unit_type* advancement_type = unit_types.find(advancement);
497  if (!advancement_type) {
498  continue;
499  }
500  average_cost_of_advanced_unit += advancement_type->cost();
501  ++counter;
502  }
503  if (counter > 0) {
504  average_cost_of_advanced_unit /= counter;
505  } else {
506  // Unit don't have advancements. Use cost of unit itself.
507  average_cost_of_advanced_unit = recall_unit->cost();
508  }
509  double xp_quantity = static_cast<double>(recall_unit->experience()) /
510  recall_unit->max_experience();
511  double recall_value = recall_unit->cost() + xp_quantity * average_cost_of_advanced_unit;
512  int cost = current_team().recall_cost();
513  if (recall_unit->recall_cost() > -1) {
514  cost=recall_unit->recall_cost();
515  }
516  if (recall_value < cost) {
517  recall_value = -1; // Unit is not worth to get recalled.
518  }
519  return recall_value;
520 }
521 
522 const std::string* recruitment::get_appropriate_recall(const std::string& type,
523  const data& leader_data) const {
524  const std::string* best_recall_id = nullptr;
525  double best_recall_value = -1;
526  for (const unit_const_ptr & recall_unit : current_team().recall_list()) {
527  if (type != recall_unit->type_id()) {
528  continue;
529  }
530  // Check if this leader is allowed to recall this unit.
531  const unit_filter ufilt(vconfig(leader_data.leader->recall_filter()));
532  if (!ufilt(*recall_unit, map_location::null_location())) {
533  LOG_AI_RECRUITMENT << "Refused recall because of filter: " << recall_unit->id() << "\n";
534  continue;
535  }
536  const double recall_value = recruitment::recall_unit_value(recall_unit);
537  if (recall_value > best_recall_value) {
538  best_recall_id = &recall_unit->id();
539  best_recall_value = recall_value;
540  }
541  }
542  return best_recall_id;
543 }
544 
545 /**
546  * A helper function for execute().
547  * Decides according to the leaders ratio scores which leader should recruit.
548  */
549 data* recruitment::get_best_leader_from_ratio_scores(std::vector<data>& leader_data,
550  const config* job) const {
551  assert(job);
552  // Find things for normalization.
553  int total_recruit_count = 0;
554  double ratio_score_sum = 0.0;
555  for (const data& data : leader_data) {
556  ratio_score_sum += data.ratio_score;
557  total_recruit_count += data.recruit_count;
558  }
559  assert(ratio_score_sum > 0.0);
560 
561  // Shuffle leader_data to break ties randomly.
562  std::shuffle(leader_data.begin(), leader_data.end(), randomness::rng::default_instance());
563 
564  // Find which leader should recruit according to ratio_scores.
565  data* best_leader_data = nullptr;
566  double biggest_difference = -99999.;
567  for (data& data : leader_data) {
568  if (!leader_matches_job(data, job)) {
569  continue;
570  }
571  double desired_ammount = data.ratio_score / ratio_score_sum * (total_recruit_count + 1);
572  double current_ammount = data.recruit_count;
573  double difference = desired_ammount - current_ammount;
574  if (difference > biggest_difference) {
575  biggest_difference = difference;
576  best_leader_data = &data;
577  }
578  }
579  return best_leader_data;
580 }
581 
582 /**
583  * A helper function for execute().
584  * Counts own units and then decides what unit should be recruited so that the
585  * unit distribution approaches the given scores.
586  */
587 const std::string recruitment::get_best_recruit_from_scores(const data& leader_data,
588  const config* job) {
589  assert(job);
590  std::string pattern_type = get_random_pattern_type_if_exists(leader_data, job);
591  if (!pattern_type.empty()) {
592  LOG_AI_RECRUITMENT << "Randomly chosen pattern_type: " << pattern_type << "\n";
593  }
594  std::string best_recruit = "";
595  double biggest_difference = -99999.;
596  for (const score_map::value_type& i : leader_data.get_normalized_scores()) {
597  const std::string& unit = i.first;
598  const double score = i.second;
599 
600  if (!limit_ok(unit)) {
601  continue;
602  }
603  if (!pattern_type.empty()) {
604  if (!recruit_matches_type(unit, pattern_type)) {
605  continue;
606  }
607  } else {
608  if (!recruit_matches_job(unit, job)) {
609  continue;
610  }
611  }
612 
613  double desired_ammount = score * (total_own_units_ + 1);
614  double current_ammount = own_units_count_[unit];
615  double difference = desired_ammount - current_ammount;
616  if (scouts_wanted_ > 0 && recruit_matches_type(unit, "scout")) {
617  difference += 1000.;
618  }
619  if (difference > biggest_difference) {
620  biggest_difference = difference;
621  best_recruit = unit;
622  }
623  }
624  return best_recruit;
625 }
626 
627 /**
628  * For Map Analysis
629  * Computes from our cost map and the combined cost map of all enemies the important hexes.
630  */
632  const pathfind::full_cost_map& my_cost_map,
633  const pathfind::full_cost_map& enemy_cost_map) {
634 
635  const gamemap& map = resources::gameboard->map();
636 
637  // First collect all hexes where the average costs are similar in important_hexes_candidates
638  // Then chose only those hexes where the average costs are relatively low.
639  // This is done to remove hexes to where the teams need a similar amount of moves but
640  // which are relatively far away comparing to other important hexes.
641  typedef std::map<map_location, double> border_cost_map;
642  border_cost_map important_hexes_candidates;
643  double smallest_border_movecost = 999999;
644  double biggest_border_movecost = 0;
645  for(int x = 0; x < map.w(); ++x) {
646  for (int y = 0; y < map.h(); ++y) {
647  double my_cost_average = my_cost_map.get_average_cost_at(x, y);
648  double enemy_cost_average = enemy_cost_map.get_average_cost_at(x, y);
649  if (my_cost_average == -1 || enemy_cost_average == -1) {
650  continue;
651  }
652  // We multiply the threshold MAP_BORDER_THICKNESS by the average_local_cost
653  // to favor high cost hexes (a bit).
654  if (std::abs(my_cost_average - MAP_OFFENSIVE_SHIFT - enemy_cost_average) <
655  MAP_BORDER_THICKNESS * average_local_cost_[map_location(x, y)]) {
656  double border_movecost = (my_cost_average + enemy_cost_average) / 2;
657 
658  important_hexes_candidates[map_location(x, y)] = border_movecost;
659 
660  if (border_movecost < smallest_border_movecost) {
661  smallest_border_movecost = border_movecost;
662  }
663  if (border_movecost > biggest_border_movecost) {
664  biggest_border_movecost = border_movecost;
665  }
666  }
667  } // for
668  } // for
669  double threshold = (biggest_border_movecost - smallest_border_movecost) *
670  MAP_BORDER_WIDTH + smallest_border_movecost;
671  for (const border_cost_map::value_type& candidate : important_hexes_candidates) {
672  if (candidate.second < threshold) {
673  important_hexes_.insert(candidate.first);
674  }
675  }
676 }
677 
678 /**
679  * For Map Analysis.
680  * Calculates for a given unit the average defense on the map.
681  * (According to important_hexes_ / important_terrain_)
682  */
683 double recruitment::get_average_defense(const std::string& u_type) const {
684  const unit_type* const u_info = unit_types.find(u_type);
685  if (!u_info) {
686  return 0.0;
687  }
688  long summed_defense = 0;
689  int total_terrains = 0;
690  for (const terrain_count_map::value_type& entry : important_terrain_) {
691  const t_translation::terrain_code& terrain = entry.first;
692  int count = entry.second;
693  int defense = 100 - u_info->movement_type().defense_modifier(terrain);
694  summed_defense += defense * count;
695  total_terrains += count;
696  }
697  double average_defense = (total_terrains == 0) ? 0.0 :
698  static_cast<double>(summed_defense) / total_terrains;
699  return average_defense;
700 }
701 
702 /**
703  * For Map Analysis.
704  * Creates cost maps for a side. Each hex is map to
705  * a) the summed movecost and
706  * b) how many units can reach this hex
707  * for all units of side.
708  */
710  const unit_map& units = resources::gameboard->units();
711  const team& team = resources::gameboard->get_team(side);
712 
713  pathfind::full_cost_map cost_map(true, true, team, true, true);
714 
715  // First add all existing units to cost_map.
716  unsigned int unit_count = 0;
717  for (const unit& unit : units) {
718  if (unit.side() != side || unit.can_recruit() ||
719  unit.incapacitated() || unit.total_movement() <= 0) {
720  continue;
721  }
722  ++unit_count;
723  cost_map.add_unit(unit);
724  }
725 
726  // If this side has not so many units yet, add unit_types with the leaders position as origin.
727  if (unit_count < UNIT_THRESHOLD) {
728  std::vector<unit_map::const_iterator> leaders = units.find_leaders(side);
729  for (const unit_map::const_iterator& leader : leaders) {
730  // First add team-recruits (it's fine when (team-)recruits are added multiple times).
731  for (const std::string& recruit : team.recruits()) {
732  cost_map.add_unit(leader->get_location(), unit_types.find(recruit), side);
733  }
734 
735  // Next add extra-recruits.
736  for (const std::string& recruit : leader->recruits()) {
737  cost_map.add_unit(leader->get_location(), unit_types.find(recruit), side);
738  }
739  }
740  }
741  return cost_map;
742 }
743 
744 /**
745  * For Map Analysis.
746  * Shows the important hexes for debugging purposes on the map. Only if debug is activated.
747  */
749  if (!game_config::debug) {
750  return;
751  }
753  for (const map_location& loc : important_hexes_) {
754  // Little hack: use map_location north from loc and make 2 linebreaks to center the "X".
755  display::get_singleton()->labels().set_label(loc.get_direction(map_location::NORTH), "\n\nX");
756  }
757 }
758 
759 /**
760  * Calculates a average lawful bonus, so Combat Analysis will work
761  * better in caves and custom time of day cycles.
762  */
764  int sum = 0;
765  int counter = 0;
766  for (const time_of_day& time : resources::tod_manager->times()) {
767  sum += time.lawful_bonus;
768  ++counter;
769  }
770  if (counter > 0) {
771  average_lawful_bonus_ = std::round(static_cast<double>(sum) / counter);
772  }
773 }
774 
775 /**
776  * For Map Analysis.
777  * Creates a map where each hex is mapped to the average cost of the terrain for our units.
778  */
780  average_local_cost_.clear();
781  const gamemap& map = resources::gameboard->map();
783 
784  for(int x = 0; x < map.w(); ++x) {
785  for (int y = 0; y < map.h(); ++y) {
786  map_location loc(x, y);
787  int summed_cost = 0;
788  int count = 0;
789  for (const std::string& recruit : team.recruits()) {
790  const unit_type* const unit_type = unit_types.find(recruit);
791  if (!unit_type) {
792  continue;
793  }
794  int cost = unit_type->movement_type().get_movement().cost(map[loc]);
795  if (cost < 99) {
796  summed_cost += cost;
797  ++count;
798  }
799  }
800  average_local_cost_[loc] = (count == 0) ? 0 : static_cast<double>(summed_cost) / count;
801  }
802  }
803 }
804 
805 /**
806  * For Map Analysis.
807  * Creates a std::set of hexes where a fight will occur with high probability.
808  */
810  important_hexes_.clear();
811  important_terrain_.clear();
813 
815  const gamemap& map = resources::gameboard->map();
816  const unit_map& units = resources::gameboard->units();
817 
818  // Mark battle areas as important
819  // This are locations where one of my units is adjacent
820  // to a enemies unit.
821  for (const unit& unit : units) {
822  if (unit.side() != get_side()) {
823  continue;
824  }
826  // We found a enemy next to us. Mark our unit and all adjacent
827  // hexes as important.
828  std::vector<map_location> surrounding;
829  get_tiles_in_radius(unit.get_location(), 1, surrounding);
831  std::copy(surrounding.begin(), surrounding.end(),
832  std::inserter(important_hexes_, important_hexes_.begin()));
834  }
835  }
836 
837  // Mark area between me and enemies as important
838  // This is done by creating a cost_map for each team.
839  // A cost_map maps to each hex the average costs to reach this hex
840  // for all units of the team.
841  // The important hexes are those where my value on the cost map is
842  // similar to a enemies one.
844  for (const team& team : resources::gameboard->teams()) {
845  if (current_team().is_enemy(team.side())) {
846  const pathfind::full_cost_map enemy_cost_map = get_cost_map_of_side(team.side());
847 
848  compare_cost_maps_and_update_important_hexes(my_cost_map, enemy_cost_map);
849  }
850  }
851 
852  // Mark 'near' villages and area around them as important
853  // To prevent a 'feedback' of important locations collect all
854  // important villages first and add them and their surroundings
855  // to important_hexes_ in a second step.
856  std::vector<map_location> important_villages;
857  for (const map_location& village : map.villages()) {
858  std::vector<map_location> surrounding;
859  get_tiles_in_radius(village, MAP_VILLAGE_NEARNESS_THRESHOLD, surrounding);
860  for (const map_location& hex : surrounding) {
861  if (important_hexes_.find(hex) != important_hexes_.end()) {
862  important_villages.push_back(village);
863  break;
864  }
865  }
866  }
867  for (const map_location& village : important_villages) {
868  important_hexes_.insert(village);
869  std::vector<map_location> surrounding;
870  get_tiles_in_radius(village, MAP_VILLAGE_SURROUNDING, surrounding);
871  for (const map_location& hex : surrounding) {
872  // only add hex if one of our units can reach the hex
873  if (map.on_board(hex) && my_cost_map.get_cost_at(hex.x, hex.y) != -1) {
874  important_hexes_.insert(hex);
875  }
876  }
877  }
878 }
879 
880 /**
881  * For Combat Analysis.
882  * Calculates how good unit-type a is against unit type b.
883  * If the value is bigger then 0, a is better then b.
884  * If the value is 2.0 then unit-type a is twice as good as unit-type b.
885  * Since this function is called very often it uses a cache.
886  */
887 double recruitment::compare_unit_types(const std::string& a, const std::string& b) {
888  const unit_type* const type_a = unit_types.find(a);
889  const unit_type* const type_b = unit_types.find(b);
890  if (!type_a || !type_b) {
891  ERR_AI_RECRUITMENT << "Couldn't find unit type: " << ((type_a) ? b : a) << "." << std::endl;
892  return 0.0;
893  }
894  double defense_a = get_average_defense(a);
895  double defense_b = get_average_defense(b);
896 
897  const double* cache_value = get_cached_combat_value(a, b, defense_a, defense_b);
898  if (cache_value) {
899  return *cache_value;
900  }
901 
902  double damage_to_a = 0.0;
903  double damage_to_b = 0.0;
904 
905  // a attacks b
906  simulate_attack(type_a, type_b, defense_a, defense_b, &damage_to_a, &damage_to_b);
907  // b attacks a
908  simulate_attack(type_b, type_a, defense_b, defense_a, &damage_to_b, &damage_to_a);
909 
910  int a_cost = (type_a->cost() > 0) ? type_a->cost() : 1;
911  int b_cost = (type_b->cost() > 0) ? type_b->cost() : 1;
912  int a_max_hp = (type_a->hitpoints() > 0) ? type_a->hitpoints() : 1;
913  int b_max_hp = (type_b->hitpoints() > 0) ? type_b->hitpoints() : 1;
914 
915  double retval = 1.;
916  // There are rare cases where a unit deals 0 damage (eg. Elvish Lady).
917  // Then we just set the value to something reasonable.
918  if (damage_to_a <= 0 && damage_to_b <= 0) {
919  retval = 0.;
920  } else if (damage_to_a <= 0) {
921  retval = 2.;
922  } else if (damage_to_b <= 0) {
923  retval = -2.;
924  } else {
925  // Normal case
926  double value_of_a = damage_to_b / (b_max_hp * a_cost);
927  double value_of_b = damage_to_a / (a_max_hp * b_cost);
928 
929  if (value_of_a > value_of_b) {
930  return value_of_a / value_of_b;
931  } else if (value_of_a < value_of_b) {
932  return -value_of_b / value_of_a;
933  } else {
934  return 0.;
935  }
936  }
937 
938  // Insert in cache.
939  const cached_combat_value entry(defense_a, defense_b, retval);
940  std::set<cached_combat_value>& cache = combat_cache_[a][b];
941  cache.insert(entry);
942 
943  return retval;
944 }
945 
946 /**
947  * Combat Analysis.
948  * Main function.
949  * Compares all enemy units with all of our possible recruits and fills
950  * the scores.
951  */
952 void recruitment::do_combat_analysis(std::vector<data>* leader_data) {
953  const unit_map& units = resources::gameboard->units();
954 
955  // Collect all enemy units (and their hp) we want to take into account in enemy_units.
956  typedef std::vector<std::pair<std::string, int>> unit_hp_vector;
957  unit_hp_vector enemy_units;
958  for (const unit& unit : units) {
959  if (!current_team().is_enemy(unit.side()) || unit.incapacitated()) {
960  continue;
961  }
962  enemy_units.emplace_back(unit.type_id(), unit.hitpoints());
963  }
964  if (enemy_units.size() < UNIT_THRESHOLD) {
965  // Use also enemies recruitment lists and insert units into enemy_units.
966  for (const team& team : resources::gameboard->teams()) {
967  if (!current_team().is_enemy(team.side())) {
968  continue;
969  }
970  std::set<std::string> possible_recruits;
971  // Add team recruits.
972  possible_recruits.insert(team.recruits().begin(), team.recruits().end());
973  // Add extra recruits.
974  const std::vector<unit_map::const_iterator> leaders = units.find_leaders(team.side());
975  for (unit_map::const_iterator leader : leaders) {
976  possible_recruits.insert(leader->recruits().begin(), leader->recruits().end());
977  }
978  // Insert set in enemy_units.
979  for (const std::string& possible_recruit : possible_recruits) {
980  const unit_type* recruit_type = unit_types.find(possible_recruit);
981  if (recruit_type) {
982  int hp = recruit_type->hitpoints();
983  enemy_units.emplace_back(possible_recruit, hp);
984  }
985  }
986  }
987  }
988 
989  for (data& leader : *leader_data) {
990  if (leader.recruits.empty()) {
991  continue;
992  }
993  typedef std::map<std::string, double> simple_score_map;
994  simple_score_map temp_scores;
995 
996  for (const unit_hp_vector::value_type& entry : enemy_units) {
997  const std::string& enemy_unit = entry.first;
998  int enemy_unit_hp = entry.second;
999  for (const std::string& recruit : leader.recruits) {
1000  double score = compare_unit_types(recruit, enemy_unit);
1001  score *= enemy_unit_hp;
1002  score = std::pow(score, COMBAT_SCORE_POWER);
1003  temp_scores[recruit] += score;
1004  }
1005  }
1006 
1007  if (temp_scores.empty()) {
1008  return;
1009  }
1010  // Find things for normalization.
1011  double max = -99999.;
1012  double sum = 0;
1013  for (const simple_score_map::value_type& entry : temp_scores) {
1014  double score = entry.second;
1015  if (score > max) {
1016  max = score;
1017  }
1018  sum += score;
1019  }
1020  double average = sum / temp_scores.size();
1021 
1022  // What we do now is a linear transformation.
1023  // We want to map the scores in temp_scores to something between 0 and 100.
1024  // The max score shall always be 100.
1025  // The min score depends on the aspect "recruitment_diversity".
1026  double new_100 = max;
1027  double score_threshold = get_recruitment_diversity();
1028  if (score_threshold <= 0) {
1029  score_threshold = 0.0001;
1030  }
1031  double new_0 = max - (score_threshold * (max - average));
1032  if (new_100 == new_0) {
1033  // This can happen if max == average. (E.g. only one possible recruit)
1034  new_0 -= 0.000001;
1035  }
1036 
1037  for (const simple_score_map::value_type& entry : temp_scores) {
1038  const std::string& recruit = entry.first;
1039  double score = entry.second;
1040 
1041  // Here we transform.
1042  // (If score <= new_0 then normalized_score will be 0)
1043  // (If score = new_100 then normalized_score will be 100)
1044  double normalized_score = 100 * ((score - new_0) / (new_100 - new_0));
1045  if (normalized_score < 0) {
1046  normalized_score = 0;
1047  }
1048  leader.scores[recruit] += normalized_score;
1049  }
1050  } // for all leaders
1051 }
1052 
1053 /**
1054  * For Combat Analysis.
1055  * Returns the cached combat value for two unit types
1056  * or nullptr if there is none or terrain defenses are not within range.
1057  */
1058 const double* recruitment::get_cached_combat_value(const std::string& a, const std::string& b,
1059  double a_defense, double b_defense) {
1060  double best_distance = 999;
1061  const double* best_value = nullptr;
1062  const std::set<cached_combat_value>& cache = combat_cache_[a][b];
1063  for (const cached_combat_value& entry : cache) {
1064  double distance_a = std::abs(entry.a_defense - a_defense);
1065  double distance_b = std::abs(entry.b_defense - b_defense);
1066  if (distance_a <= COMBAT_CACHE_TOLERANCY && distance_b <= COMBAT_CACHE_TOLERANCY) {
1067  if(distance_a + distance_b <= best_distance) {
1068  best_distance = distance_a + distance_b;
1069  best_value = &entry.value;
1070  }
1071  }
1072  }
1073  return best_value;
1074 }
1075 
1076 /**
1077  * For Combat Analysis.
1078  * This struct encapsulates all information for one attack simulation.
1079  * One attack simulation is defined by the unit-types, the weapons and the units defenses.
1080  */
1088 
1089  attack_simulation(const unit_type* attacker, const unit_type* defender,
1090  double attacker_defense, double defender_defense,
1091  const_attack_ptr att_weapon, const_attack_ptr def_weapon,
1092  int average_lawful_bonus) :
1093  attacker_type(attacker),
1094  defender_type(defender),
1095  attacker_stats(attacker, att_weapon, true, defender, def_weapon,
1096  std::round(defender_defense), average_lawful_bonus),
1097  defender_stats(defender, def_weapon, false, attacker, att_weapon,
1098  std::round(attacker_defense), average_lawful_bonus),
1099  attacker_combatant(attacker_stats),
1100  defender_combatant(defender_stats)
1101  {
1102  attacker_combatant.fight(defender_combatant);
1103  }
1104 
1105  bool better_result(const attack_simulation* other, bool for_defender) {
1106  assert(other);
1107  if (for_defender) {
1109  defender_combatant, attacker_combatant,
1110  other->defender_combatant, other->attacker_combatant, 0);
1111  } else {
1113  attacker_combatant, defender_combatant,
1114  other->attacker_combatant, other->defender_combatant, 0);
1115  }
1116  }
1117 
1118  double get_avg_hp_of_defender() const {
1119  return get_avg_hp_of_combatant(false);
1120  }
1121 
1122  double get_avg_hp_of_attacker() const {
1123  return get_avg_hp_of_combatant(true);
1124  }
1125  double get_avg_hp_of_combatant(bool attacker) const {
1126  const combatant& combatant = (attacker) ? attacker_combatant : defender_combatant;
1127  const unit_type* unit_type = (attacker) ? attacker_type : defender_type;
1128  double avg_hp = combatant.average_hp(0);
1129 
1130  // handle poisson
1131  avg_hp -= combatant.poisoned * game_config::poison_amount;
1132 
1133  avg_hp = std::max(0., avg_hp);
1134  avg_hp = std::min(static_cast<double>(unit_type->hitpoints()), avg_hp);
1135  return avg_hp;
1136  }
1137 };
1138 
1139 /**
1140  * For Combat Analysis.
1141  * Simulates a attack with a attacker and a defender.
1142  * The function will use battle_context::better_combat() to decide which weapon to use.
1143  */
1145  const unit_type* const attacker, const unit_type* const defender,
1146  double attacker_defense, double defender_defense,
1147  double* damage_to_attacker, double* damage_to_defender) const {
1148  if(!attacker || !defender || !damage_to_attacker || !damage_to_defender) {
1149  ERR_AI_RECRUITMENT << "nullptr pointer in simulate_attack()" << std::endl;
1150  return;
1151  }
1152  const_attack_itors attacker_weapons = attacker->attacks();
1153  const_attack_itors defender_weapons = defender->attacks();
1154 
1155  std::shared_ptr<attack_simulation> best_att_attack;
1156 
1157  // Let attacker choose weapon
1158  for (const attack_type& att_weapon : attacker_weapons) {
1159  std::shared_ptr<attack_simulation> best_def_response;
1160  // Let defender choose weapon
1161  for (const attack_type& def_weapon : defender_weapons) {
1162  if (att_weapon.range() != def_weapon.range()) {
1163  continue;
1164  }
1165  auto simulation = std::make_shared<attack_simulation>(
1166  attacker, defender,
1167  attacker_defense, defender_defense,
1168  att_weapon.shared_from_this(), def_weapon.shared_from_this(), average_lawful_bonus_);
1169  if (!best_def_response || simulation->better_result(best_def_response.get(), true)) {
1170  best_def_response = simulation;
1171  }
1172  } // for defender weapons
1173 
1174  if (!best_def_response) {
1175  // Defender can not fight back. Simulate this as well.
1176  best_def_response.reset(new attack_simulation(
1177  attacker, defender,
1178  attacker_defense, defender_defense,
1179  att_weapon.shared_from_this(), nullptr, average_lawful_bonus_));
1180  }
1181  if (!best_att_attack || best_def_response->better_result(best_att_attack.get(), false)) {
1182  best_att_attack = best_def_response;
1183  }
1184  } // for attacker weapons
1185 
1186  if (!best_att_attack) {
1187  return;
1188  }
1189 
1190  *damage_to_defender += (defender->hitpoints() - best_att_attack->get_avg_hp_of_defender());
1191  *damage_to_attacker += (attacker->hitpoints() - best_att_attack->get_avg_hp_of_attacker());
1192 }
1193 
1194 /**
1195  * For Configuration / Aspect "recruitment-instructions"
1196  * We call a [recruit] tag a "job".
1197  */
1199  config* most_important_job = nullptr;
1200  int most_important_importance = -1;
1201  int biggest_number = -1;
1202  for (config& job : recruitment_instructions_.child_range("recruit")) {
1203  if (job.empty()) {
1204  continue;
1205  }
1206  int importance = job["importance"].to_int(1);
1207  int number = job["number"].to_int(99999);
1208  bool total = job["total"].to_bool(false);
1209  if (total) {
1210  // If the total flag is set we have to subtract
1211  // all existing units which matches the type.
1213  for (const count_map::value_type& entry : own_units_count_) {
1214  const std::string& unit_type = entry.first;
1215  const int count = entry.second;
1216  if (recruit_matches_job(unit_type, &job)) {
1217  number = number - count;
1218  }
1219  }
1220  }
1221  if (number <= 0) {
1222  continue;
1223  }
1224  if (importance > most_important_importance ||
1225  (importance == most_important_importance && biggest_number > number)) {
1226  most_important_job = &job;
1227  most_important_importance = importance;
1228  biggest_number = number;
1229  }
1230  }
1231  return most_important_job;
1232 }
1233 
1234 /**
1235  * For Configuration / Aspect "recruitment-instructions"
1236  * If the flag pattern is set, this method returns a random element of the
1237  * type-attribute.
1238  */
1239 const std::string recruitment::get_random_pattern_type_if_exists(const data& leader_data,
1240  const config* job) const {
1241  std::string choosen_type;
1242  if (job->operator[]("pattern").to_bool(false)) {
1243  std::vector<std::string> job_types = utils::split(job->operator[]("type"));
1244 
1245  if (job_types.empty()) {
1246  // Empty type attribute means random recruiting.
1247  // Fill job_types with recruitment list.
1248  std::copy(leader_data.recruits.begin(), leader_data.recruits.end(),
1249  std::back_inserter(job_types));
1250  }
1251 
1252  // Before we choose a random pattern type, we make sure that at least one recruit
1253  // matches the types and doesn't exceed the [limit].
1254  // We do this by erasing elements of job_types.
1255  std::vector<std::string>::iterator job_types_it = job_types.begin();
1256 
1257  // Iteration through all elements.
1258  while (job_types_it != job_types.end()) {
1259  bool type_ok = false;
1260  for (const std::string& recruit : leader_data.recruits) {
1261  if (recruit_matches_type(recruit, *job_types_it) && limit_ok(recruit)) {
1262  type_ok = true;
1263  break;
1264  }
1265  }
1266  if (type_ok) {
1267  ++job_types_it;
1268  } else {
1269  // Erase Element. erase() will return iterator of next element.
1270  LOG_AI_RECRUITMENT << "Erase type " << *job_types_it << " from pattern.\n";
1271  job_types_it = job_types.erase(job_types_it);
1272  }
1273  }
1274 
1275  if (!job_types.empty()) {
1276  // Choose a random job_type.
1277  choosen_type = job_types[randomness::generator->get_random_int(0, job_types.size()-1)];
1278  }
1279  }
1280  return choosen_type;
1281 }
1282 
1283 /**
1284  * For Configuration / Aspect "recruitment_pattern"
1285  * Converts the (old) recruitment_pattern into a recruitment_instruction (job).
1286  */
1288  const std::vector<std::string> recruitment_pattern = get_recruitment_pattern();
1289  if (recruitment_pattern.empty()) {
1290  return;
1291  }
1292  // Create a job (recruitment_instruction).
1293  config job;
1294  std::stringstream s;
1295  for (std::vector<std::string>::const_iterator type = recruitment_pattern.begin();
1296  type != recruitment_pattern.end(); ++type) {
1297  s << *type;
1298  if (type != recruitment_pattern.end() - 1) { // Avoid trailing comma.
1299  s << ", ";
1300  }
1301  }
1302  job["type"] = s.str();
1303  job["number"] = 99999;
1304  job["pattern"] = true;
1305  job["blocker"] = true;
1306  job["total"] = false;
1307  job["importance"] = 1;
1308  recruitment_instructions_.add_child("recruit", job);
1309 }
1310 
1311 /**
1312  * For Configuration / Aspect "recruitment-instructions"
1313  * Checks if a given leader is specified in the "leader_id" attribute.
1314  */
1315 bool recruitment::leader_matches_job(const data& leader_data, const config* job) const {
1316  assert(job);
1317  // First we make sure that this leader can recruit
1318  // at least one unit-type specified in the job.
1319  bool is_ok = false;
1320  for (const std::string& recruit : leader_data.recruits) {
1321  if (recruit_matches_job(recruit, job) && limit_ok(recruit)) {
1322  is_ok = true;
1323  break;
1324  }
1325  }
1326  if (!is_ok) {
1327  return false;
1328  }
1329 
1330  std::vector<std::string> ids = utils::split(job->operator[]("leader_id"));
1331  if (ids.empty()) {
1332  // If no leader is specified, all leaders are okay.
1333  return true;
1334  }
1335  return (std::find(ids.begin(), ids.end(), leader_data.leader->id()) != ids.end());
1336 }
1337 
1338 /**
1339  * For Configuration / Aspect "recruitment-instructions"
1340  * Checks if a recruit-type can be recruited according to the [limit]-tag.
1341  */
1342 bool recruitment::limit_ok(const std::string& recruit) const {
1343  // We don't use the member recruitment_instruction_ but instead
1344  // retrieve the aspect again. So the [limit]s can be altered during a turn.
1346 
1347  for (const config& limit : aspect.child_range("limit")) {
1348  std::vector<std::string> types = utils::split(limit["type"]);
1349  // First check if the recruit matches one of the types.
1350  if (recruit_matches_types(recruit, types)) {
1351  // Count all own existing units which matches the type.
1352  int count = 0;
1353  for (const count_map::value_type& entry : own_units_count_) {
1354  const std::string& unit = entry.first;
1355  int number = entry.second;
1356  if (recruit_matches_types(unit, types)) {
1357  count += number;
1358  }
1359  }
1360  // Check if we reached the limit.
1361  if (count >= limit["max"].to_int(0)) {
1362  return false;
1363  }
1364  }
1365  }
1366  return true;
1367 }
1368 
1369 /**
1370  * For Configuration / Aspect "recruitment-instructions"
1371  * Checks if a given recruit-type is specified in the "type" attribute.
1372  */
1373 bool recruitment::recruit_matches_job(const std::string& recruit, const config* job) const {
1374  assert(job);
1375  std::vector<std::string> job_types = utils::split(job->operator[]("type"));
1376  return recruit_matches_types(recruit, job_types);
1377 }
1378 
1379 /**
1380  * For Configuration / Aspect "recruitment-instructions"
1381  * Checks if a given recruit-type matches one atomic "type" attribute.
1382  */
1383 bool recruitment::recruit_matches_type(const std::string& recruit, const std::string& type) const {
1384  const unit_type* recruit_type = unit_types.find(recruit);
1385  if (!recruit_type) {
1386  return false;
1387  }
1388  // Consider type-name.
1389  if (recruit_type->id() == type) {
1390  return true;
1391  }
1392  // Consider usage.
1393  if (recruit_type->usage() == type) {
1394  return true;
1395  }
1396  // Consider level.
1397  std::stringstream s;
1398  s << recruit_type->level();
1399  if (s.str() == type) {
1400  return true;
1401  }
1402  return false;
1403 }
1404 
1405 /**
1406  * For Configuration / Aspect "recruitment-instructions"
1407  * Checks if a given recruit-type matches one of the given types.
1408  */
1409 bool recruitment::recruit_matches_types(const std::string& recruit,
1410  const std::vector<std::string>& types) const {
1411  // If no type is specified, all recruits are okay.
1412  if (types.empty()) {
1413  return true;
1414  }
1415  for (const std::string& type : types) {
1416  if (recruit_matches_type(recruit, type)) {
1417  return true;
1418  }
1419  }
1420  return false;
1421 }
1422 
1423 /**
1424  * For Configuration / Aspect "recruitment-instructions"
1425  */
1427  assert(job);
1428  if ((*job)["blocker"].to_bool(true)) {
1429  LOG_AI_RECRUITMENT << "Canceling job.\n";
1430  job->clear();
1431  return true;
1432  } else {
1433  LOG_AI_RECRUITMENT << "Aborting recruitment.\n";
1434  return false;
1435  }
1436 }
1437 
1438 /**
1439  * For Aspect "recruitment_save_gold".
1440  * Guess the income over the next turns.
1441  * This doesn't need to be exact. In the end we are just interested if this value is
1442  * positive or negative.
1443  */
1446  const std::size_t own_villages = team.villages().size();
1447  const double village_gain = get_estimated_village_gain();
1448  const double unit_gain = get_estimated_unit_gain();
1449 
1450  double total_income = 0;
1451  for (int i = 1; i <= turns; ++i) {
1452  double income = (own_villages + village_gain * i) * game_config::village_income;
1453  double upkeep = resources::gameboard->side_upkeep(get_side()) + unit_gain * i -
1454  (own_villages + village_gain * i) * game_config::village_support;
1455  double resulting_income = team.base_income() + income - std::max(0., upkeep);
1456  total_income += resulting_income;
1457  }
1458  return total_income;
1459 }
1460 
1461 /**
1462  * For Aspect "recruitment_save_gold".
1463  * Guess how many units we will gain / loose over the next turns per turn.
1464  */
1466  return - own_units_in_combat_counter_ / 3.;
1467 }
1468 
1469 /**
1470  * For Aspect "recruitment_save_gold".
1471  * Guess how many villages we will gain over the next turns per turn.
1472  */
1474  const gamemap& map = resources::gameboard->map();
1475  int neutral_villages = 0;
1476  for (const map_location& village : map.villages()) {
1477  if (resources::gameboard->village_owner(village) == -1) {
1478  ++neutral_villages;
1479  }
1480  }
1481  return (neutral_villages / resources::gameboard->teams().size()) / 4.;
1482 }
1483 
1484 /**
1485  * For Aspect "recruitment_save_gold".
1486  * Returns our_total_unit_costs / enemy_total_unit_costs.
1487  */
1489  const unit_map& units = resources::gameboard->units();
1490  double own_total_value = 0.;
1491  double team_total_value = 0.;
1492  double enemy_total_value = 0.;
1493  for (const unit& unit : units) {
1494  if (unit.incapacitated() || unit.total_movement() <= 0 || unit.can_recruit()) {
1495  continue;
1496  }
1497  double value = unit.cost() *
1498  static_cast<double>(unit.hitpoints()) / static_cast<double>(unit.max_hitpoints());
1499  if (current_team().is_enemy(unit.side())) {
1500  enemy_total_value += value;
1501  } else {
1502  team_total_value += value;
1503  if (unit.side() == current_team().side()) {
1504  own_total_value += value;
1505  }
1506  }
1507  }
1508  int allies_count = 0;
1509  for (const team& team : resources::gameboard->teams()) {
1510  if (!current_team().is_enemy(team.side())) {
1511  ++allies_count;
1512  }
1513  }
1514  // If only the leader is left, the values could be 0.
1515  // Catch those cases and return something reasonable.
1516  if ((own_total_value == 0. || team_total_value == 0) && enemy_total_value == 0.) {
1517  return 0.; // do recruit
1518  } else if (enemy_total_value == 0.) {
1519  return 999.; // save money
1520  }
1521 
1522  // We calculate two ratios: One for the team and one for just our self.
1523  // Then we return the minimum.
1524  // This prevents cases where side1 will recruit until the save_gold begin threshold
1525  // is reached, and side2 won't recruit anything. (assuming side1 and side2 are allied)
1526  double own_ratio = (own_total_value / enemy_total_value) * allies_count;
1527  double team_ratio = team_total_value / enemy_total_value;
1528  return std::min<double>(own_ratio, team_ratio);
1529 }
1530 
1531 /**
1532  * For Aspect "recruitment_save_gold".
1533  * Main method.
1534  */
1537  return;
1538  }
1539  // Retrieve from aspect.
1540  int spend_all_gold = get_recruitment_save_gold()["spend_all_gold"].to_int(-1);
1541  if (spend_all_gold > 0 && current_team().gold() >= spend_all_gold) {
1543  LOG_AI_RECRUITMENT << "Changed state_ to SPEND_ALL_GOLD. \n";
1544  return;
1545  }
1546  double ratio = get_unit_ratio();
1547  double income_estimation = 1.;
1548  if (!get_recruitment_save_gold()["save_on_negative_income"].to_bool(false)) {
1549  income_estimation = get_estimated_income(SAVE_GOLD_FORECAST_TURNS);
1550  }
1551  LOG_AI_RECRUITMENT << "Ratio is " << ratio << "\n";
1552  LOG_AI_RECRUITMENT << "Estimated income is " << income_estimation << "\n";
1553 
1554  // Retrieve from aspect.
1555  double save_gold_begin = get_recruitment_save_gold()["begin"].to_double(1.5);
1556  double save_gold_end = get_recruitment_save_gold()["end"].to_double(1.1);
1557 
1558  if (state_ == NORMAL && ratio > save_gold_begin && income_estimation > 0) {
1559  state_ = SAVE_GOLD;
1560  LOG_AI_RECRUITMENT << "Changed state to SAVE_GOLD.\n";
1561  } else if (state_ == SAVE_GOLD && ratio < save_gold_end) {
1562  state_ = NORMAL;
1563  LOG_AI_RECRUITMENT << "Changed state to NORMAL.\n";
1564  }
1565 }
1566 
1567 /**
1568  * Will add a random value between 0 and "recruitment_randomness"
1569  * to all recruits
1570  */
1571 void recruitment::do_randomness(std::vector<data>* leader_data) const {
1572  if (!leader_data) {
1573  return;
1574  }
1575  for (data& data : *leader_data) {
1576  for (score_map::value_type& entry : data.scores) {
1577  double& score = entry.second;
1579  }
1580  }
1581 }
1582 
1583 /**
1584  * Will give a penalty to similar units. Similar units are units in one advancement tree.
1585  * Example (Archer can advance to Ranger):
1586  * before after
1587  * Elvish Fighter: 50 50
1588  * Elvish Archer: 50 25
1589  * Elvish Ranger: 50 25
1590  */
1591 void recruitment::do_similarity_penalty(std::vector<data>* leader_data) const {
1592  if (!leader_data) {
1593  return;
1594  }
1595  for (data& data : *leader_data) {
1596  // First we count how many similarities each recruit have to other ones (in a map).
1597  // Some examples:
1598  // If unit A and unit B have nothing to do with each other, they have similarity = 0.
1599  // If A advances to B both have similarity = 1.
1600  // If A advances to B and B to C, A, B and C have similarity = 2.
1601  // If A advances to B or C, A have similarity = 2. B and C have similarity = 1.
1602  typedef std::map<std::string, int> similarity_map;
1603  similarity_map similarities;
1604  for (const score_map::value_type& entry : data.scores) {
1605  const std::string& recruit = entry.first;
1606  const unit_type* recruit_type = unit_types.find(recruit);
1607  if (!recruit_type) {
1608  continue;
1609  }
1610  for (const std::string& advanced_type : recruit_type->advancement_tree()) {
1611  if (data.scores.count(advanced_type) != 0) {
1612  ++similarities[recruit];
1613  ++similarities[advanced_type];
1614  }
1615  }
1616  }
1617  // Now we divide each score by similarity + 1.
1618  for (score_map::value_type& entry : data.scores) {
1619  const std::string& recruit = entry.first;
1620  double& score = entry.second;
1621  score /= (similarities[recruit] + 1);
1622  }
1623  }
1624 }
1625 
1626 /**
1627  * Called at the beginning and whenever the recruitment list changes.
1628  */
1630  std::map<std::size_t, int>::const_iterator it = cheapest_unit_costs_.find(leader->underlying_id());
1631  if (it != cheapest_unit_costs_.end()) {
1632  return it->second;
1633  }
1634 
1635  int cheapest_cost = 999999;
1636 
1637  // team recruits
1638  for (const std::string& recruit : current_team().recruits()) {
1639  const unit_type* const info = unit_types.find(recruit);
1640  if (!info) {
1641  continue;
1642  }
1643  if (info->cost() < cheapest_cost) {
1644  cheapest_cost = info->cost();
1645  }
1646  }
1647  // extra recruits
1648  for (const std::string& recruit : leader->recruits()) {
1649  const unit_type* const info = unit_types.find(recruit);
1650  if (!info) {
1651  continue;
1652  }
1653  if (info->cost() < cheapest_cost) {
1654  cheapest_cost = info->cost();
1655  }
1656  }
1657  // Consider recall costs.
1658  if (!current_team().recall_list().empty() && current_team().recall_cost() < cheapest_cost) {
1659  cheapest_cost = current_team().recall_cost();
1660  }
1661  LOG_AI_RECRUITMENT << "Cheapest unit cost updated to " << cheapest_cost << ".\n";
1662  cheapest_unit_costs_[leader->underlying_id()] = cheapest_cost;
1663  return cheapest_cost;
1664 }
1665 
1666 /**
1667  * For Aspect "recruitment_more"
1668  */
1669 void recruitment::handle_recruitment_more(std::vector<data>* leader_data) const {
1670  if (!leader_data) {
1671  return;
1672  }
1673  const std::vector<std::string> aspect = get_recruitment_more();
1674  for (const std::string& type : aspect) {
1675  for (data& data : *leader_data) {
1676  for (score_map::value_type& entry : data.scores) {
1677  const std::string& recruit = entry.first;
1678  double& score = entry.second;
1679  if (recruit_matches_type(recruit, type)) {
1680  score += 25.;
1681  }
1682  }
1683  }
1684  }
1685 }
1686 
1687 /**
1688  * Helper function.
1689  * Returns true if there is a enemy within the radius.
1690  */
1691 bool recruitment::is_enemy_in_radius(const map_location& loc, int radius) const {
1692  const unit_map& units = resources::gameboard->units();
1693  std::vector<map_location> surrounding;
1694  get_tiles_in_radius(loc, radius, surrounding);
1695  if (surrounding.empty()) {
1696  return false;
1697  }
1698  for (const map_location& l : surrounding) {
1699  const unit_map::const_iterator& enemy_it = units.find(l);
1700  if(enemy_it == units.end()) {
1701  continue;
1702  }
1703  if (!current_team().is_enemy(enemy_it->side()) || enemy_it->incapacitated()) {
1704  continue;
1705  }
1706  return true;
1707  }
1708  return false;
1709 }
1710 
1711 /*
1712  * Helper Function.
1713  * Counts own units on the map and saves the result
1714  * in member own_units_count_
1715  */
1717  own_units_count_.clear();
1718  total_own_units_ = 0;
1719  const unit_map& units = resources::gameboard->units();
1720  for (const unit& unit : units) {
1721  if (unit.side() != get_side() || unit.can_recruit() ||
1722  unit.incapacitated() || unit.total_movement() <= 0) {
1723  continue;
1724  }
1726  ++total_own_units_;
1727  }
1728 }
1729 
1730 /**
1731  * This function will use the aspect villages_per_scout to decide how many
1732  * scouts we want to recruit.
1733  */
1735  scouts_wanted_ = 0;
1736  if (get_villages_per_scout() == 0) {
1737  return;
1738  }
1739  int neutral_villages = 0;
1740  // We recruit the initial allocation of scouts
1741  // based on how many neutral villages there are.
1742  for (const map_location& village : resources::gameboard->map().villages()) {
1743  if (resources::gameboard->village_owner(village) == -1) {
1744  ++neutral_villages;
1745  }
1746  }
1747  double our_share = static_cast<double>(neutral_villages) / resources::gameboard->teams().size();
1748 
1749  // The villages per scout is for a two-side battle,
1750  // accounting for all neutral villages on the map.
1751  // We only look at our share of villages, so we halve it,
1752  // making us get twice as many scouts.
1753  double villages_per_scout = (VILLAGE_PER_SCOUT_MULTIPLICATOR * get_villages_per_scout()) / 2;
1754 
1755  scouts_wanted_ = (villages_per_scout > 0) ? std::round(our_share / villages_per_scout) : 0;
1756 
1757  if (scouts_wanted_ == 0) {
1758  return;
1759  }
1760 
1761  // Subtract already recruited scouts.
1762  for (const count_map::value_type& entry : own_units_count_) {
1763  const std::string& unit_type = entry.first;
1764  const int count = entry.second;
1765  if (recruit_matches_type(unit_type, "scout")) {
1766  scouts_wanted_ -= count;
1767  }
1768  }
1769 }
1770 
1771 /**
1772  * Observer Code
1773  */
1775  : recruit_list_changed_(false), gamestate_changed_(0) {
1778 }
1779 
1781  const std::string& event) {
1782  if (event == "ai_recruit_list_changed") {
1783  LOG_AI_RECRUITMENT << "Recruitment List is not valid anymore.\n";
1785  } else {
1787  }
1788 }
1789 
1793 }
1794 
1796  return recruit_list_changed_;
1797 }
1798 
1800  recruit_list_changed_ = changed;
1801 }
1802 
1804  return gamestate_changed_;
1805 }
1806 
1808  gamestate_changed_ = 0;
1809 }
1810 
1811 recruitment_aspect::recruitment_aspect(readonly_context &context, const config &cfg, const std::string &id)
1812  : standard_aspect<config>(context, cfg, id)
1813 {
1814  config parsed_cfg(cfg.has_child("value") ? cfg.child("value") : cfg);
1815  // First, transform simplified tags into [recruit] tags.
1816  for (config pattern : parsed_cfg.child_range("pattern")) {
1817  parsed_cfg["pattern"] = true;
1818  parsed_cfg.add_child("recruit", std::move(pattern));
1819  }
1820  for (config total : parsed_cfg.child_range("total")) {
1821  parsed_cfg["total"] = true;
1822  parsed_cfg.add_child("recruit", std::move(total));
1823  }
1824  parsed_cfg.clear_children("pattern", "total");
1825  // Then, if there's no [recruit], add one.
1826  if (!parsed_cfg.has_child("recruit")) {
1827  parsed_cfg.add_child("recruit", config {"importance", 0});
1828  }
1829  // Finally, populate our lists
1830  for (config job : parsed_cfg.child_range("recruit")) {
1831  create_job(jobs_, job);
1832  }
1833  for (config lim : parsed_cfg.child_range("limit")) {
1834  create_limit(limits_, lim);
1835  }
1836  std::function<void(std::vector<std::shared_ptr<recruit_job>>&, const config&)> factory_jobs =
1837  std::bind(&recruitment_aspect::create_job,*this,_1,_2);
1838  std::function<void(std::vector<std::shared_ptr<recruit_limit>>&, const config&)> factory_limits =
1839  std::bind(&recruitment_aspect::create_limit,*this,_1,_2);
1840  register_vector_property(property_handlers(), "recruit", jobs_, factory_jobs);
1841  register_vector_property(property_handlers(), "limit", limits_, factory_limits);
1842 }
1843 
1845  config cfg;
1846  for (const std::shared_ptr<recruit_job>& job : jobs_) {
1847  cfg.add_child("recruit", job->to_config());
1848  }
1849  for (const std::shared_ptr<recruit_limit>& lim : limits_) {
1850  cfg.add_child("limit", lim->to_config());
1851  }
1852  *this->value_ = cfg;
1853  this->valid_ = true;
1854 }
1855 
1856 void recruitment_aspect::create_job(std::vector<std::shared_ptr<recruit_job>> &jobs, const config &job) {
1857  jobs.emplace_back(std::make_shared<recruit_job>(
1858  utils::split(job["type"]),
1859  job["leader_id"], job["id"],
1860  job["number"].to_int(-1), job["importance"].to_int(1),
1861  job["total"].to_bool(false),
1862  job["blocker"].to_bool(true),
1863  job["pattern"].to_bool(true)
1864  ));
1865 }
1866 
1867 void recruitment_aspect::create_limit(std::vector<std::shared_ptr<recruit_limit>> &limits, const config &lim) {
1868  limits.emplace_back(std::make_shared<recruit_limit>(
1869  utils::split(lim["type"]),
1870  lim["id"],
1871  lim["max"].to_int(0)
1872  ));
1873 }
1874 
1875 } // namespace default_recruitment
1876 } // namespace ai
std::shared_ptr< action_result > action_result_ptr
Definition: game_info.hpp:78
int defense_modifier(const t_translation::terrain_code &terrain) const
Returns the defensive value of the indicated terrain.
Definition: movetype.hpp:267
boost::intrusive_ptr< const unit > unit_const_ptr
Definition: ptr.hpp:30
bool recall_unit(const std::string &id, team &current_team, const map_location &loc, const map_location &from, map_location::DIRECTION facing, bool show, bool use_undo)
Recalls the unit with the indicated ID for the provided team.
Definition: create.cpp:740
const double * get_cached_combat_value(const std::string &a, const std::string &b, double a_defense, double b_defense)
For Combat Analysis.
double get_avg_hp_of_combatant(bool attacker) const
config & child(config_key_type key, int n=0)
Returns the nth child with the given key, or a reference to an invalid config if there is none...
Definition: config.cpp:420
::tod_manager * tod_manager
Definition: resources.cpp:29
virtual int get_villages_per_scout() const override
Definition: contexts.hpp:863
attack_simulation(const unit_type *attacker, const unit_type *defender, double attacker_defense, double defender_defense, const_attack_ptr att_weapon, const_attack_ptr def_weapon, int average_lawful_bonus)
int h() const
Effective map height, in hexes.
Definition: map.hpp:128
std::vector< unit_iterator > find_leaders(int side)
Definition: map.cpp:357
unit_iterator end()
Definition: map.hpp:415
double get_average_defense(const std::string &unit_type) const
For Map Analysis.
static display * get_singleton()
Returns the display object if a display object exists.
Definition: display.hpp:88
const unit_type * find(const std::string &key, unit_type::BUILD_STATUS status=unit_type::FULL) const
Finds a unit_type by its id() and makes sure it is built to the specified level.
Definition: types.cpp:1271
virtual const unit_map & units() const override
Definition: game_board.hpp:114
void clear_children(T... keys)
Definition: config.hpp:479
int village_support
Definition: game_config.cpp:55
void update_average_local_cost()
For Map Analysis.
This class represents a single unit of a specific type.
Definition: unit.hpp:106
double get_estimated_unit_gain() const
For Aspect "recruitment_save_gold".
bool remove_job_if_no_blocker(config *job)
For Configuration / Aspect "recruitment-instructions".
map_location find_vacant_castle(const unit &leader)
Wrapper for find_vacant_tile() when looking for a vacant castle tile near a leader.
Definition: pathfind.cpp:119
bool better_result(const attack_simulation *other, bool for_defender)
static manager & get_singleton()
Definition: manager.hpp:151
virtual void execute()
Execute the candidate action.
#define ERR_AI_RECRUITMENT
Definition: recruitment.cpp:50
Various functions that implement attacks and attack calculations.
virtual const config get_recruitment_save_gold() const override
Definition: contexts.hpp:827
#define LOG_AI_RECRUITMENT
Definition: recruitment.cpp:49
static bool better_combat(const combatant &us_a, const combatant &them_a, const combatant &us_b, const combatant &them_b, double harm_weight)
Definition: attack.cpp:489
void create_job(std::vector< std::shared_ptr< recruit_job >> &jobs, const config &job)
int cost(const t_translation::terrain_code &terrain, bool slowed=false) const
Returns the cost associated with the given terrain.
Definition: movetype.hpp:60
logger & info()
Definition: log.cpp:90
#define a
Managing the AI-Game interaction - AI actions and their results.
int hitpoints() const
The current number of hitpoints this unit has.
Definition: unit.hpp:473
bool has_child(config_key_type key) const
Determine whether a config has a child or not.
Definition: config.cpp:412
virtual int get_recruitment_randomness() const override
Definition: contexts.hpp:821
void get_tiles_in_radius(const map_location &center, const int radius, std::vector< map_location > &result)
Function that will add to result all locations within radius tiles of center (excluding center itself...
Definition: pathutils.cpp:55
property_handler_map & property_handlers()
Definition: component.cpp:132
void create_limit(std::vector< std::shared_ptr< recruit_limit >> &limits, const config &lim)
child_itors child_range(config_key_type key)
Definition: config.cpp:362
double get_random_double()
This helper method returns a floating-point number in the range [0,1[.
Definition: random.cpp:111
std::map< map_location, double > average_local_cost_
double average_hp(unsigned int healing=0) const
What&#39;s the average hp (weighted average of hp_dist).
void update_important_hexes()
For Map Analysis.
virtual const gamemap & map() const override
Definition: game_board.hpp:109
std::vector< std::shared_ptr< recruit_job > > jobs_
A terrain string which is converted to a terrain is a string with 1 or 2 layers the layers are separa...
Definition: translation.hpp:50
unit_type_data unit_types
Definition: types.cpp:1529
STL namespace.
void update_scouts_wanted()
This function will use the aspect villages_per_scout to decide how many scouts we want to recruit...
std::set< std::string > advancement_tree() const
Get the advancement tree.
Definition: types.cpp:672
const std::string * get_appropriate_recall(const std::string &type, const data &leader_data) const
std::shared_ptr< recruit_result > recruit_result_ptr
Definition: game_info.hpp:83
bool on_board(const map_location &loc) const
Tell if a location is on the map.
Definition: map.cpp:377
int get_cheapest_unit_cost_for_leader(const unit_map::const_iterator &leader)
Called at the beginning and whenever the recruitment list changes.
const std::string & type_id() const
The id of this unit&#39;s type.
Definition: unit.hpp:334
void clear()
Definition: config.cpp:863
void add_unit(const unit &u, bool use_max_moves=true)
Adds a units cost map to cost_map (increments the elements in cost_map)
Definition: pathfind.cpp:911
std::shared_ptr< config > value_
Definition: aspect.hpp:191
const std::string get_best_recruit_from_scores(const data &leader_data, const config *job)
A helper function for execute().
-file sdl_utils.hpp
double get_average_cost_at(int x, int y) const
Accessor for the costs.
Definition: pathfind.cpp:991
const std::string get_random_pattern_type_if_exists(const data &leader_data, const config *job) const
For Configuration / Aspect "recruitment-instructions" If the flag pattern is set, this method returns...
recruit_situation_change_observer recruit_situation_change_observer_
std::vector< std::string > split(const std::string &val, const char c, const int flags)
Splits a (comma-)separated string into a vector of pieces.
static void register_vector_property(property_handler_map &property_handlers, const std::string &property, std::vector< std::shared_ptr< X >> &values, std::function< void(std::vector< std::shared_ptr< X >> &, const config &)> construction_factory)
int cost() const
How much gold is required to recruit this unit.
Definition: unit.hpp:611
A single unit type that the player may recruit.
Definition: types.hpp:42
void do_similarity_penalty(std::vector< data > *leader_data) const
Will give a penalty to similar units.
std::set< map_location > important_hexes_
double compare_unit_types(const std::string &a, const std::string &b)
For Combat Analysis.
void show_important_hexes() const
For Map Analysis.
const battle_context_unit_stats attacker_stats
virtual const std::vector< std::string > get_recruitment_more() const override
Definition: contexts.hpp:809
#define b
double get_estimated_income(int turns) const
For Aspect "recruitment_save_gold".
Object which defines a time of day with associated bonuses, image, sounds etc.
Definition: time_of_day.hpp:57
double get_unit_ratio() const
For Aspect "recruitment_save_gold".
This class stores all the data for a single &#39;side&#39; (in game nomenclature).
Definition: team.hpp:44
A small explanation about what&#39;s going on here: Each action has access to two game_info objects First...
Definition: actions.cpp:58
void remove_gamestate_observer(events::observer *event_observer)
Removes an observer of game events except ai_user_interact event and ai_sync_network event...
Definition: manager.cpp:358
team & get_team(int i)
Definition: game_board.hpp:104
std::shared_ptr< recall_result > recall_result_ptr
Definition: game_info.hpp:82
int cost() const
Definition: types.hpp:161
int get_cost_at(int x, int y) const
Accessor for the costs.
Definition: pathfind.cpp:980
void update_average_lawful_bonus()
Calculates a average lawful bonus, so Combat Analysis will work better in caves and custom time of da...
const movetype & movement_type() const
Definition: types.hpp:177
const terrain_label * set_label(const map_location &loc, const t_string &text, const int creator=-1, const std::string &team="", const color_t color=font::NORMAL_COLOR, const bool visible_in_fog=true, const bool visible_in_shroud=false, const bool immutable=false, const std::string &category="", const t_string &tooltip="")
Definition: label.cpp:146
void handle_recruitment_more(std::vector< data > *leader_data) const
For Aspect "recruitment_more".
const terrain_costs & get_movement() const
Definition: movetype.hpp:245
virtual recall_result_ptr check_recall_action(const std::string &id, const map_location &where=map_location::null_location(), const map_location &from=map_location::null_location()) override
Definition: contexts.hpp:556
bool is_allowed_unit(const unit &u) const
Flag indicating whether unit may be used by this candidate action.
Definition: rca.cpp:93
void integrate_recruitment_pattern_in_recruitment_instructions()
For Configuration / Aspect "recruitment_pattern" Converts the (old) recruitment_pattern into a recrui...
const std::string & usage() const
Definition: types.hpp:164
int side_upkeep(int side_num) const
const pathfind::full_cost_map get_cost_map_of_side(int side) const
For Map Analysis.
game_board * gameboard
Definition: resources.cpp:20
virtual double get_recruitment_diversity() const override
Definition: contexts.hpp:797
config * get_most_important_job()
For Configuration / Aspect "recruitment-instructions" We call a [recruit] tag a "job".
Encapsulates the map of the game.
Definition: map.hpp:36
score_map get_normalized_scores() const
Definition: recruitment.hpp:69
bool limit_ok(const std::string &recruit) const
For Configuration / Aspect "recruitment-instructions" Checks if a recruit-type can be recruited accor...
bool is_enemy(int n) const
Definition: team.hpp:243
void fight(combatant &opponent, bool levelup_considered=true)
Simulate a fight! Can be called multiple times for cumulative calculations.
virtual const move_map & get_enemy_dstsrc() const override
Definition: contexts.hpp:694
const std::string & id() const
The id for this unit_type.
Definition: types.hpp:138
Managing the AIs lifecycle - headers TODO: Refactor history handling and internal commands...
map_display and display: classes which take care of displaying the map and game-data on the screen...
virtual const std::vector< std::string > get_recruitment_pattern() const override
Definition: contexts.hpp:815
Structure describing the statistics of a unit involved in the battle.
Definition: attack.hpp:48
Recruitment Engine by flix See https://wiki.wesnoth.org/AI_Recruitment.
bool recruit_matches_types(const std::string &recruit, const std::vector< std::string > &types) const
For Configuration / Aspect "recruitment-instructions" Checks if a given recruit-type matches one of t...
double get_estimated_village_gain() const
For Aspect "recruitment_save_gold".
void do_combat_analysis(std::vector< data > *leader_data)
Combat Analysis.
static const ::config * terrain
The terrain used to create the cache.
Definition: minimap.cpp:130
virtual recruit_result_ptr check_recruit_action(const std::string &unit_name, const map_location &where=map_location::null_location(), const map_location &from=map_location::null_location()) override
Definition: contexts.hpp:563
void simulate_attack(const unit_type *const attacker, const unit_type *const defender, double attacker_defense, double defender_defense, double *damage_to_attacker, double *damage_to_defender) const
For Combat Analysis.
double recall_unit_value(const unit_const_ptr &recall_unit) const
A helper function for execute().
action_result_ptr execute_recall(const std::string &id, data &leader_data)
A helper function for execute().
int recall_cost() const
Definition: team.hpp:193
Encapsulates the map of the game.
Definition: location.hpp:42
std::string to_string() const
unit_iterator find(std::size_t id)
Definition: map.cpp:311
All combat-related info.
int w() const
Effective map width, in hexes.
Definition: map.hpp:125
data * get_best_leader_from_ratio_scores(std::vector< data > &leader_data, const config *job) const
A helper function for execute().
std::size_t i
Definition: function.cpp:933
std::stringstream & wml_error()
Use this logger to send errors due to deprecated WML.
Definition: log.cpp:269
virtual const team & current_team() const override
Definition: contexts.hpp:530
int max_hitpoints() const
The max number of hitpoints this unit can have.
Definition: unit.hpp:479
bool recruit_matches_type(const std::string &recruit, const std::string &type) const
For Configuration / Aspect "recruitment-instructions" Checks if a given recruit-type matches one atom...
virtual config to_config() const
serialize
Definition: rca.cpp:107
int village_income
Definition: game_config.cpp:54
void compare_cost_maps_and_update_important_hexes(const pathfind::full_cost_map &my_cost_map, const pathfind::full_cost_map &enemy_cost_map)
For Map Analysis Computes from our cost map and the combined cost map of all enemies the important he...
static map_location::DIRECTION s
static tcache cache
Definition: minimap.cpp:134
Structure which uses find_routes() to build a cost map This maps each hex to a the movements a unit w...
Definition: pathfind.hpp:266
bool can_recruit() const
Whether this unit can recruit other units - ie, are they a leader unit.
Definition: unit.hpp:590
bool is_enemy_in_radius(const map_location &loc, int radius) const
Helper function.
virtual double power_projection(const map_location &loc, const move_map &dstsrc) const override
Function which finds how much &#39;power&#39; a side can attack a certain location with.
Definition: contexts.hpp:791
action_result_ptr execute_recruit(const std::string &type, data &leader_data)
A helper function for execute().
void add_recruit_list_changed_observer(events::observer *event_observer)
Adds an observer of &#39;ai_recruit_list_changed&#39; event.
Definition: manager.cpp:382
virtual side_number get_side() const override
Get the side number.
Definition: contexts.hpp:471
std::vector< std::shared_ptr< recruit_limit > > limits_
int level() const
Definition: types.hpp:153
int get_random_int(int min, int max)
This helper method provides a random int from the underlying generator, using results of next_random...
Definition: random.hpp:51
const bool & debug
int hitpoints() const
Definition: types.hpp:150
bool recruit_matches_job(const std::string &recruit, const config *job) const
For Configuration / Aspect "recruitment-instructions" Checks if a given recruit-type is specified in ...
rng * generator
This generator is automatically synced during synced context.
Definition: random.cpp:60
config & add_child(config_key_type key)
Definition: config.cpp:476
bool valid_
Definition: aspect.hpp:96
int turns()
Definition: game.cpp:583
bool leader_matches_job(const data &leader_data, const config *job) const
For Configuration / Aspect "recruitment-instructions" Checks if a given leader is specified in the "l...
bool find(E event, F functor)
Tests whether an event handler is available.
recruitment(rca_context &context, const config &cfg)
const std::vector< map_location > & villages() const
Return a list of the locations of villages on the map.
Definition: map.hpp:192
const map_location & get_location() const
The current map location this unit is at.
Definition: unit.hpp:1320
void add_gamestate_observer(events::observer *event_observer)
Adds observer of game events except ai_user_interact event and ai_sync_network event.
Definition: manager.cpp:351
A variable-expanding proxy for the config class.
Definition: variable.hpp:44
static lg::log_domain log_ai_recruitment("ai/recruitment")
Standard logging facilities (interface).
static const map_location & null_location()
Definition: location.hpp:85
recruitment_aspect(readonly_context &context, const config &cfg, const std::string &id)
virtual const config get_recruitment_instructions() const override
Definition: contexts.hpp:803
static const double BAD_SCORE
Definition: rca.hpp:32
Container associating units to locations.
Definition: map.hpp:99
bool incapacitated() const
Check if the unit has been petrified.
Definition: unit.hpp:881
int total_movement() const
The maximum moves this unit has.
Definition: unit.hpp:1229
config to_config() const
serialize
int base_income() const
Definition: team.hpp:191
map_labels & labels()
Definition: display.cpp:2540
int turn() const
retval
Default window/dialog return values.
Definition: retval.hpp:28
int side() const
The side this unit belongs to.
Definition: unit.hpp:311
std::vector< game_tip > shuffle(const std::vector< game_tip > &tips)
Shuffles the tips.
Definition: tips.cpp:46
void clear_all()
Definition: label.cpp:239
unit_map::const_iterator leader
Definition: recruitment.hpp:48
const_attack_itors attacks() const
Definition: types.cpp:509
boost::iterator_range< boost::indirect_iterator< attack_list::const_iterator > > const_attack_itors
int side() const
Definition: team.hpp:188
A config object defines a single node in a WML file, with access to child nodes.
Definition: config.hpp:68
virtual double evaluate()
Evaluate the candidate action, resetting the internal state of the action.
void do_randomness(std::vector< data > *leader_data) const
Will add a random value between 0 and "recruitment_randomness" to all recruits.
std::shared_ptr< const attack_type > const_attack_ptr
Definition: ptr.hpp:37
void update_state()
For Aspect "recruitment_save_gold".
double get_score() const
Get the usual score of the candidate action without re-evaluation.
Definition: rca.cpp:77
const std::set< map_location > & villages() const
Definition: team.hpp:184
This module contains various pathfinding functions and utilities.
static rng & default_instance()
Definition: random.cpp:73
const battle_context_unit_stats defender_stats
void remove_recruit_list_changed_observer(events::observer *event_observer)
Deletes an observer of &#39;ai_recruit_list_changed&#39; event.
Definition: manager.cpp:394
std::string::const_iterator iterator
Definition: tokenizer.hpp:24
std::set< std::string > recruits
Definition: recruitment.hpp:49
double poisoned
Resulting chance we are poisoned.
const std::set< std::string > & recruits() const
Definition: team.hpp:223
candidate action framework
std::map< std::size_t, int > cheapest_unit_costs_