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