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