The Battle for Wesnoth  1.15.0-dev
ca.cpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2009 - 2018 by Yurii Chernyi <terraninfo@terraninfo.net>
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  * Default AI (Testing)
17  * @file
18  */
19 
20 #include "ai/default/ca.hpp"
21 #include "ai/actions.hpp"
22 #include "ai/manager.hpp"
23 #include "ai/composite/engine.hpp"
24 #include "ai/composite/rca.hpp"
25 #include "ai/composite/stage.hpp"
26 #include "game_board.hpp"
27 #include "game_classification.hpp"
28 #include "game_data.hpp"
29 #include "log.hpp"
30 #include "map/map.hpp"
31 #include "resources.hpp"
32 #include "team.hpp"
33 #include "units/unit.hpp"
34 #include "pathfind/pathfind.hpp"
35 #include "pathfind/teleport.hpp"
36 
37 #include <numeric>
38 #include <boost/dynamic_bitset.hpp>
39 
40 #include <SDL_timer.h>
41 
42 static lg::log_domain log_ai_testing_ai_default("ai/ca/testing_ai_default");
43 #define DBG_AI_TESTING_AI_DEFAULT LOG_STREAM(debug, log_ai_testing_ai_default)
44 #define LOG_AI_TESTING_AI_DEFAULT LOG_STREAM(info, log_ai_testing_ai_default)
45 #define WRN_AI_TESTING_AI_DEFAULT LOG_STREAM(warn, log_ai_testing_ai_default)
46 #define ERR_AI_TESTING_AI_DEFAULT LOG_STREAM(err, log_ai_testing_ai_default)
47 
48 
49 namespace ai {
50 
51 namespace ai_default_rca {
52 
53 //==============================================================
54 
55 goto_phase::goto_phase( rca_context &context, const config &cfg )
56  : candidate_action(context,cfg)
57  , move_()
58 {
59 }
60 
62 {
63 }
64 
66 {
67  // Execute goto-movements - first collect gotos in a list
68  std::vector<map_location> gotos;
69  unit_map &units_ = resources::gameboard->units();
70  const gamemap &map_ = resources::gameboard->map();
71 
72  for(unit_map::iterator ui = units_.begin(); ui != units_.end(); ++ui) {
73  if (ui->get_goto() == ui->get_location()) {
74  ui->set_goto(map_location());
75  } else if (ui->side() == get_side() && map_.on_board(ui->get_goto())) {
76  gotos.push_back(ui->get_location());
77  }
78  }
79 
80  for(std::vector<map_location>::const_iterator g = gotos.begin(); g != gotos.end(); ++g) {
81  unit_map::const_iterator ui = units_.find(*g);
82  // passive_leader: never moves or attacks
83  if(ui->can_recruit() && get_passive_leader() && !get_passive_leader_shares_keep()){
84  continue;
85  }
86  // end of passive_leader
87 
89 
91 
93  route = pathfind::a_star_search(ui->get_location(), ui->get_goto(), 10000.0, calc, map_.w(), map_.h(), &allowed_teleports);
94 
95  if (!route.steps.empty()){
96  move_ = check_move_action(ui->get_location(), route.steps.back(), true, true);
97  } else {
98  // there is no direct path (yet)
99  // go to the nearest hex instead.
100  // maybe a door will open later or something
101 
102  int closest_distance = -1;
103  std::pair<map_location,map_location> closest_move;
104  for(move_map::const_iterator i = get_dstsrc().begin(); i != get_dstsrc().end(); ++i) {
105  if(i->second != ui->get_location()) {
106  continue;
107  }
108  int distance = distance_between(i->first,ui->get_goto());
109  if(closest_distance == -1 || distance < closest_distance) {
110  closest_distance = distance;
111  closest_move = *i;
112  }
113  }
114  if(closest_distance != -1) {
115  move_ = check_move_action(ui->get_location(), closest_move.first);
116  } else {
117  continue;
118  }
119  }
120 
121  if (move_->is_ok()) {
122  return get_score();
123  }
124  }
125 
126  return BAD_SCORE;
127 }
128 
130 {
131  if (!move_) {
132  return;
133  }
134 
135  move_->execute();
136  if (!move_->is_ok()){
137  LOG_AI_TESTING_AI_DEFAULT << get_name() << "::execute not ok" << std::endl;
138  }
139 
140  // In some situations, a theoretically possible path is blocked by allies,
141  // resulting in the unit not moving. In this case, we remove all remaining
142  // movement from the unit in order to prevent blacklisting of the CA.
143  if (!move_->is_gamestate_changed()){
144  LOG_AI_TESTING_AI_DEFAULT << get_name() << "::execute did not move unit; removing moves instead" << std::endl;
145  stopunit_result_ptr stopunit = check_stopunit_action(move_->get_unit_location(), true, false);
146  stopunit->execute();
147  }
148 }
149 
150 
151 //==============================================================
152 
154  : candidate_action(context,cfg),best_analysis_(),choice_rating_(-1000.0)
155 {
156 }
157 
159 {
160 }
161 
163 {
164  std::vector<std::string> options = get_recruitment_pattern();
165 
166  choice_rating_ = -1000.0;
167  int ticks = SDL_GetTicks();
168 
169  const std::vector<attack_analysis> analysis = get_attacks(); //passive_leader: in aspect_attacks::analyze_targets()
170 
171  int time_taken = SDL_GetTicks() - ticks;
172  LOG_AI_TESTING_AI_DEFAULT << "took " << time_taken << " ticks for " << analysis.size()
173  << " positions. Analyzing...\n";
174 
175  ticks = SDL_GetTicks();
176 
177  const int max_sims = 50000;
178  int num_sims = analysis.empty() ? 0 : max_sims/analysis.size();
179  if(num_sims < 20)
180  num_sims = 20;
181  if(num_sims > 40)
182  num_sims = 40;
183 
184  LOG_AI_TESTING_AI_DEFAULT << "simulations: " << num_sims << "\n";
185 
186  const int max_positions = 30000;
187  const int skip_num = analysis.size()/max_positions;
188 
189  std::vector<attack_analysis>::const_iterator choice_it = analysis.end();
190  for(std::vector<attack_analysis>::const_iterator it = analysis.begin();
191  it != analysis.end(); ++it) {
192 
193  if(skip_num > 0 && ((it - analysis.begin())%skip_num) && it->movements.size() > 1)
194  continue;
195 
196  const double rating = it->rating(get_aggression(),*this);
197  LOG_AI_TESTING_AI_DEFAULT << "attack option rated at " << rating << " ("
198  << (it->uses_leader ? get_leader_aggression() : get_aggression()) << ")\n";
199 
200  if(rating > choice_rating_) {
201  choice_it = it;
202  choice_rating_ = rating;
203  }
204  }
205 
206  time_taken = SDL_GetTicks() - ticks;
207  LOG_AI_TESTING_AI_DEFAULT << "analysis took " << time_taken << " ticks\n";
208 
209 
210  // suokko tested the rating against current_team().caution()
211  // Bad mistake -- the AI became extremely reluctant to attack anything.
212  // Documenting this in case someone has this bright idea again...*don't*...
213  if(choice_rating_ > 0.0) {
214  best_analysis_ = *choice_it;
215  return get_score();
216  } else {
217  return BAD_SCORE;
218  }
219 }
220 
222 {
223  assert(choice_rating_ > 0.0);
224  map_location from = best_analysis_.movements[0].first;
225  map_location to = best_analysis_.movements[0].second;
226  map_location target_loc = best_analysis_.target;
227 
228  if (from!=to) {
229  move_result_ptr move_res = execute_move_action(from,to,false);
230  if (!move_res->is_ok()) {
231  LOG_AI_TESTING_AI_DEFAULT << get_name() << "::execute not ok, move failed" << std::endl;
232  return;
233  }
234  }
235 
236  attack_result_ptr attack_res = check_attack_action(to, target_loc, -1);
237  if (!attack_res->is_ok()) {
238  LOG_AI_TESTING_AI_DEFAULT << get_name() << "::execute not ok, attack cancelled" << std::endl;
239  } else {
240  attack_res->execute();
241  if (!attack_res->is_ok()) {
242  LOG_AI_TESTING_AI_DEFAULT << get_name() << "::execute not ok, attack failed" << std::endl;
243  }
244  }
245 
246 }
247 
248 //==============================================================
249 
251  : candidate_action(context,cfg), auto_remove_(), dst_(), id_(), move_()
252 {
253 }
254 
256 {
257 }
258 
260 {
261 
262  const config &goal = get_leader_goal();
263  //passive leader can reach a goal
264  if (!goal) {
265  LOG_AI_TESTING_AI_DEFAULT << get_name() << "No goal found\n";
266  return BAD_SCORE;
267  }
268 
269  if (goal.empty()) {
270  LOG_AI_TESTING_AI_DEFAULT << get_name() << "Empty goal found\n";
271  return BAD_SCORE;
272  }
273 
274  double max_risk = goal["max_risk"].to_double(1 - get_caution());
275  auto_remove_ = goal["auto_remove"].to_bool();
276 
278  if (!dst_.valid()) {
279  ERR_AI_TESTING_AI_DEFAULT << "Invalid goal: "<<std::endl<<goal;
280  return BAD_SCORE;
281  }
282 
284  if (!leader.valid() || leader->incapacitated()) {
285  WRN_AI_TESTING_AI_DEFAULT << "Leader not found" << std::endl;
286  return BAD_SCORE;
287  }
288 
289  id_ = goal["id"].str();
290  if (leader->get_location() == dst_) {
291  //goal already reached
292  if (auto_remove_ && !id_.empty()) {
293  remove_goal(id_);
294  } else {
295  move_ = check_move_action(leader->get_location(), leader->get_location(), !auto_remove_);//we do full moves if we don't want to remove goal
296  if (move_->is_ok()) {
297  return get_score();
298  } else {
299  return BAD_SCORE;
300  }
301  }
302  }
303 
305  const pathfind::teleport_map allowed_teleports = pathfind::get_teleport_locations(*leader, current_team());
306  pathfind::plain_route route = a_star_search(leader->get_location(), dst_, 1000.0, calc,
307  resources::gameboard->map().w(), resources::gameboard->map().h(), &allowed_teleports);
308  if(route.steps.empty()) {
309  LOG_AI_TESTING_AI_DEFAULT << "route empty";
310  return BAD_SCORE;
311  }
312 
313  const pathfind::paths leader_paths(*leader, false, true, current_team());
314 
315  std::map<map_location,pathfind::paths> possible_moves;
316  possible_moves.emplace(leader->get_location(), leader_paths);
317 
318  map_location loc;
319  for (const map_location &l : route.steps)
320  {
321  if (leader_paths.destinations.contains(l) &&
322  power_projection(l, get_enemy_dstsrc()) < leader->hitpoints() * max_risk)
323  {
324  loc = l;
325  }
326  }
327 
328  if(loc.valid()) {
329  move_ = check_move_action(leader->get_location(), loc, false);
330  if (move_->is_ok()) {
331  return get_score();
332  }
333  }
334  return BAD_SCORE;
335 
336 }
337 
339 {
340  move_->execute();
341  if (!move_->is_ok()){
342  LOG_AI_TESTING_AI_DEFAULT << get_name() << "::execute not ok" << std::endl;
343  }
344  if (move_->get_unit_location()==dst_) {
345  //goal already reached
346  if (auto_remove_ && !id_.empty()) {
347  remove_goal(id_);
348  }
349  }
350 }
351 
352 void move_leader_to_goals_phase::remove_goal(const std::string &id)
353 {
354  config mod_ai;
355  mod_ai["side"] = get_side();
356  mod_ai["path"] = "aspect[leader_goal].facet["+id+"]";
357  mod_ai["action"] = "delete";
359 }
360 
361 //==============================================================
362 
364  : candidate_action(context,cfg),move_()
365 {
366 
367 }
368 
370 {
371 
372 }
373 
375 {
376  if (get_leader_ignores_keep()) {
377  return BAD_SCORE;
378  }
380  return BAD_SCORE;
381  }
382 
383  // 1. Collect all leaders in a list
384  // 2. Get the suitable_keep for each leader
385  // 3. Choose the leader with the nearest suitable_keep (and which still have moves)
386  // 4. If leader can reach this keep in 1 turn -> set move_ to there
387  // 5. If not -> Calculate the best move_ (use a-star search)
388  // 6. Save move_ for execution
389 
390  // 1.
391  const unit_map &units_ = resources::gameboard->units();
392  const std::vector<unit_map::const_iterator> leaders = units_.find_leaders(get_side());
393  if (leaders.empty()) {
394  return BAD_SCORE;
395  }
396 
397  // 2. + 3.
398  const unit* best_leader = nullptr;
399  map_location best_keep;
400  int shortest_distance = 99999;
401 
402  for (const unit_map::const_iterator& leader : leaders) {
403  if (leader->incapacitated() || leader->movement_left() == 0) {
404  continue;
405  }
406 
407  // Find where the leader can move
408  const ai::moves_map &possible_moves = get_possible_moves();
409  const ai::moves_map::const_iterator& p_it = possible_moves.find(leader->get_location());
410  if (p_it == possible_moves.end()) {
411  return BAD_SCORE;
412  }
413  const pathfind::paths leader_paths = p_it->second;
414 
415  const map_location& keep = suitable_keep(leader->get_location(), leader_paths);
416  if (keep == map_location::null_location() || keep == leader->get_location()) {
417  continue;
418  }
419 
421 
422  const pathfind::teleport_map allowed_teleports = pathfind::get_teleport_locations(*leader, current_team());
423 
424  pathfind::plain_route route;
425  route = pathfind::a_star_search(leader->get_location(), keep, 10000.0, calc, resources::gameboard->map().w(), resources::gameboard->map().h(), &allowed_teleports);
426 
427  if (!route.steps.empty() || route.move_cost < shortest_distance) {
428  best_leader = &(*leader);
429  best_keep = keep;
430  shortest_distance = route.move_cost;
431  }
432  }
433 
434  if (best_leader == nullptr) {
435  return BAD_SCORE;
436  }
437 
438  // 4.
439  const unit* leader = best_leader;
440  const map_location keep = best_keep;
441  const pathfind::paths leader_paths(*leader, false, true, current_team());
443  const pathfind::teleport_map allowed_teleports = pathfind::get_teleport_locations(*leader, current_team());
444 
445  if (leader_paths.destinations.contains(keep) && units_.count(keep) == 0) {
446  move_ = check_move_action(leader->get_location(), keep, false);
447  if (move_->is_ok()) {
448  return get_score();
449  }
450  }
451 
452  // 5.
453  // The leader can't move to his keep, try to move to the closest location
454  // to the keep where there are no enemies in range.
455  // Make a map of the possible locations the leader can move to,
456  // ordered by the distance from the keep.
457  typedef std::multimap<int, map_location> ordered_locations;
458  ordered_locations moves_toward_keep;
459 
460  pathfind::plain_route route;
461  route = pathfind::a_star_search(leader->get_location(), keep, 10000.0, calc, resources::gameboard->map().w(), resources::gameboard->map().h(), &allowed_teleports);
462 
463  // find next hop
465  int next_hop_cost = 0;
466  for (const map_location& step : route.steps) {
467  if (leader_paths.destinations.contains(step)) {
468  next_hop = step;
469  next_hop_cost += leader->movement_cost(resources::gameboard->map().get_terrain(step));
470  } else {
471  break;
472  }
473  }
474  if (next_hop == map_location::null_location()) {
475  return BAD_SCORE;
476  }
477  //define the next hop to have the lowest cost (0)
478  moves_toward_keep.emplace(0, next_hop);
479 
480  for (const pathfind::paths::step &dest : leader_paths.destinations) {
481  if (!units_.find(dest.curr).valid()) {
482  route = pathfind::a_star_search(dest.curr, next_hop, 10000.0, calc,
483  resources::gameboard->map().w(), resources::gameboard->map().h(), &allowed_teleports);
484  if (route.move_cost < next_hop_cost) {
485  moves_toward_keep.emplace(route.move_cost, dest.curr);
486  }
487  }
488  }
489 
490  // Find the first location which we can move to,
491  // without the threat of enemies.
492  for (const ordered_locations::value_type& pair : moves_toward_keep) {
493  const map_location& loc = pair.second;
494  if (get_enemy_dstsrc().count(loc) == 0) {
495  move_ = check_move_action(leader->get_location(), loc, true);
496  if (move_->is_ok()) {
497  return get_score();
498  }
499  }
500  }
501  return BAD_SCORE;
502 }
503 
505 {
506  move_->execute();
507  if (!move_->is_ok()) {
508  LOG_AI_TESTING_AI_DEFAULT << get_name() <<"::execute not ok" << std::endl;
509  }
510 }
511 
512 //==============================================================
513 
515  : candidate_action(context,cfg)
516  , keep_loc_()
517  , leader_loc_()
518  , best_leader_loc_()
519  , debug_(false)
520  , moves_()
521 {
522 }
523 
525 {
526 }
527 
529 {
530  moves_.clear();
533  if (!moves_.empty()) {
534  return get_score();
535  }
536  return BAD_SCORE;
537 }
538 
539 
541 {
542  unit_map &units_ = resources::gameboard->units();
543  unit_map::const_iterator leader = units_.find_leader(get_side());
544  // Move all the units to get villages, however move the leader last,
545  // so that the castle will be cleared if it wants to stop to recruit along the way.
546  std::pair<map_location,map_location> leader_move;
547 
548  for(tmoves::const_iterator i = moves_.begin(); i != moves_.end(); ++i) {
549 
550  if(leader != units_.end() && leader->get_location() == i->second) {
551  leader_move = *i;
552  } else {
553  if (resources::gameboard->find_visible_unit(i->first, current_team()) == units_.end()) {
554  move_result_ptr move_res = execute_move_action(i->second,i->first,true);
555  if (!move_res->is_ok()) {
556  return;
557  }
558 
559  const map_location loc = move_res->get_unit_location();
560  leader = units_.find_leader(get_side());
561  const unit_map::const_iterator new_unit = units_.find(loc);
562 
563  if (new_unit != units_.end() &&
564  power_projection(i->first, get_enemy_dstsrc()) >= new_unit->hitpoints() / 4.0)
565  {
566  LOG_AI_TESTING_AI_DEFAULT << "found support target... " << new_unit->get_location() << '\n';
567  }
568  }
569  }
570  }
571 
572  if(leader_move.second.valid()) {
573  if((resources::gameboard->find_visible_unit(leader_move.first , current_team()) == units_.end())
574  && resources::gameboard->map().is_village(leader_move.first)) {
575  move_result_ptr move_res = execute_move_action(leader_move.second,leader_move.first,true);
576  if (!move_res->is_ok()) {
577  return;
578  }
579  }
580  }
581 
582  return;
583 }
584 
586  const move_map& dstsrc, const move_map& enemy_dstsrc,
587  unit_map::const_iterator &leader)
588 {
589  DBG_AI_TESTING_AI_DEFAULT << "deciding which villages we want...\n";
590  unit_map &units_ = resources::gameboard->units();
591  const int ticks = SDL_GetTicks();
593  if(leader != units_.end()) {
594  keep_loc_ = nearest_keep(leader->get_location());
595  leader_loc_ = leader->get_location();
596  } else {
599  }
600 
602 
603  // Find our units who can move.
604  treachmap reachmap;
605  for(unit_map::const_iterator u_itor = units_.begin();
606  u_itor != units_.end(); ++u_itor) {
607  if(u_itor->can_recruit() && get_passive_leader()){
608  continue;
609  }
610  if(u_itor->side() == get_side() && u_itor->movement_left()) {
611  reachmap.emplace(u_itor->get_location(), std::vector<map_location>());
612  }
613  }
614 
615 
616  DBG_AI_TESTING_AI_DEFAULT << reachmap.size() << " units found who can try to capture a village.\n";
617 
618  find_villages(reachmap, moves_, dstsrc, enemy_dstsrc);
619 
620  treachmap::iterator itor = reachmap.begin();
621  while(itor != reachmap.end()) {
622  if(itor->second.empty()) {
623  itor = remove_unit(reachmap, moves_, itor);
624  } else {
625  ++itor;
626  }
627  }
628 
629  if(!reachmap.empty()) {
630  DBG_AI_TESTING_AI_DEFAULT << reachmap.size() << " units left after removing the ones who "
631  "can't reach a village, send the to the dispatcher.\n";
632 
633  dump_reachmap(reachmap);
634 
635  dispatch(reachmap, moves_);
636  } else {
637  DBG_AI_TESTING_AI_DEFAULT << "No more units left after removing the ones who can't reach a village.\n";
638  }
639 
640  LOG_AI_TESTING_AI_DEFAULT << "Village assignment done: " << (SDL_GetTicks() - ticks)
641  << " ms, resulted in " << moves_.size() << " units being dispatched.\n";
642 
643 }
644 
646  treachmap& reachmap,
647  tmoves& moves,
648  const std::multimap<map_location,map_location>& dstsrc,
649  const std::multimap<map_location,map_location>& enemy_dstsrc)
650 
651 {
652  std::map<map_location, double> vulnerability;
653 
654  const bool passive_leader = get_passive_leader();
655 
656  std::size_t min_distance = 100000;
657  const gamemap &map_ = resources::gameboard->map();
658  std::vector<team> &teams_ = resources::gameboard->teams();
659 
660  // When a unit is dispatched we need to make sure we don't
661  // dispatch this unit a second time, so store them here.
662  std::vector<map_location> dispatched_units;
663  for(std::multimap<map_location, map_location>::const_iterator
664  j = dstsrc.begin();
665  j != dstsrc.end(); ++j) {
666 
667  const map_location &current_loc = j->first;
668 
669  if(j->second == leader_loc_) {
670  if(passive_leader) {
671  continue;
672  }
673 
674  const std::size_t distance = distance_between(keep_loc_, current_loc);
675  if(distance < min_distance) {
676  min_distance = distance;
677  best_leader_loc_ = current_loc;
678  }
679  }
680 
681  if(std::find(dispatched_units.begin(), dispatched_units.end(),
682  j->second) != dispatched_units.end()) {
683  continue;
684  }
685 
686  if(map_.is_village(current_loc) == false) {
687  continue;
688  }
689 
690  bool want_village = true, owned = false;
691  for(std::size_t n = 0; n != teams_.size(); ++n) {
692  owned = teams_[n].owns_village(current_loc);
693  if(owned && !current_team().is_enemy(n+1)) {
694  want_village = false;
695  }
696 
697  if(owned) {
698  break;
699  }
700  }
701 
702  if(want_village == false) {
703  continue;
704  }
705 
706  // If it is a neutral village, and we have no leader,
707  // then the village is of no use to us, and we don't want it.
708  if(!owned && leader_loc_ == map_location::null_location()) {
709  continue;
710  }
711 
712  double threat = 0.0;
713  const std::map<map_location,double>::const_iterator vuln = vulnerability.find(current_loc);
714  if(vuln != vulnerability.end()) {
715  threat = vuln->second;
716  } else {
717  threat = power_projection(current_loc,enemy_dstsrc);
718  vulnerability.emplace(current_loc, threat);
719  }
720 
722  if (u == resources::gameboard->units().end() || u->get_state("guardian")) {
723  continue;
724  }
725 
726  const unit &un = *u;
727  //FIXME: suokko turned this 2:1 to 1.5:1.0.
728  //and dropped the second term of the multiplication. Is that better?
729  //const double threat_multipler = (current_loc == leader_loc?2:1) * current_team().caution() * 10;
730  if(un.hitpoints() < (threat*2*un.defense_modifier(map_.get_terrain(current_loc)))/100) {
731  continue;
732  }
733 
734  // If the next and previous destination differs from our current destination,
735  // we're the only one who can reach the village -> dispatch.
736  std::multimap<map_location, map_location>::const_iterator next = j;
737  ++next; // j + 1 fails
738  const bool at_begin = (j == dstsrc.begin());
739  std::multimap<map_location, map_location>::const_iterator prev = j; //FIXME seems not to work
740  if(!at_begin) {
741  --prev;
742  }
743 #if 1
744  if((next == dstsrc.end() || next->first != current_loc)
745  && (at_begin || prev->first != current_loc)) {
746 
747  move_result_ptr move_check_res = check_move_action(j->second,j->first,true);
748  if (move_check_res->is_ok()) {
749  DBG_AI_TESTING_AI_DEFAULT << "Dispatched unit at " << j->second << " to village " << j->first << '\n';
750  moves.emplace_back(j->first, j->second);
751  }
752  reachmap.erase(j->second);
753  dispatched_units.push_back(j->second);
754  continue;
755  }
756 #endif
757  reachmap[j->second].push_back(current_loc);
758  }
759 
760  DBG_AI_TESTING_AI_DEFAULT << moves.size() << " units already dispatched, "
761  << reachmap.size() << " left to evaluate.\n";
762 }
763 
765 {
766  DBG_AI_TESTING_AI_DEFAULT << "Starting simple dispatch.\n";
767 
768  // we now have a list with units with the villages they can reach.
769  // keep trying the following steps as long as one of them changes
770  // the state.
771  // 1. Dispatch units who can reach 1 village (if more units can reach that
772  // village only one can capture it, so use the first in the list.)
773  // 2. Villages which can only be reached by one unit get that unit dispatched
774  // to them.
775  std::size_t village_count = 0;
776  bool dispatched = true;
777  while(dispatched) {
778  dispatched = false;
779 
780  if(dispatch_unit_simple(reachmap, moves)) {
781  dispatched = true;
782  } else {
783  if(reachmap.empty()) {
784  DBG_AI_TESTING_AI_DEFAULT << "dispatch_unit_simple() found a final solution.\n";
785  break;
786  } else {
787  DBG_AI_TESTING_AI_DEFAULT << "dispatch_unit_simple() couldn't dispatch more units.\n";
788  }
789  }
790 
791  if(dispatch_village_simple(reachmap, moves, village_count)) {
792  dispatched = true;
793  } else {
794  if(reachmap.empty()) {
795  DBG_AI_TESTING_AI_DEFAULT << "dispatch_village_simple() found a final solution.\n";
796  break;
797  } else {
798  DBG_AI_TESTING_AI_DEFAULT << "dispatch_village_simple() couldn't dispatch more units.\n";
799  }
800  }
801 
802  if(!reachmap.empty() && dispatched) {
803  DBG_AI_TESTING_AI_DEFAULT << reachmap.size() << " unit(s) left restarting simple dispatching.\n";
804 
805  dump_reachmap(reachmap);
806  }
807  }
808 
809  if(reachmap.empty()) {
810  DBG_AI_TESTING_AI_DEFAULT << "No units left after simple dispatcher.\n";
811  return;
812  }
813 
814  DBG_AI_TESTING_AI_DEFAULT << reachmap.size() << " units left for complex dispatch with "
815  << village_count << " villages left.\n";
816 
817  dump_reachmap(reachmap);
818 
819  dispatch_complex(reachmap, moves, village_count);
820 }
821 
822 // Returns need further processing
823 // false Nothing has been modified or no units left
825 {
826  bool result = false;
827 
828  treachmap::iterator itor = reachmap.begin();
829  while(itor != reachmap.end()) {
830  if(itor->second.size() == 1) {
831  const map_location village = itor->second[0];
832  result = true;
833 
834  DBG_AI_TESTING_AI_DEFAULT << "Dispatched unit at " << itor->first << " to village " << village << '\n';
835  moves.emplace_back(village, itor->first);
836  reachmap.erase(itor++);
837 
838  if(remove_village(reachmap, moves, village)) {
839  itor = reachmap.begin();
840  }
841 
842  } else {
843  ++itor;
844  }
845  }
846 
847  // Test special cases.
848  if(reachmap.empty()) {
849  // We're done.
850  return false;
851  }
852 
853  if(reachmap.size() == 1) {
854  // One unit left.
855  DBG_AI_TESTING_AI_DEFAULT << "Dispatched _last_ unit at " << reachmap.begin()->first
856  << " to village " << reachmap.begin()->second[0] << '\n';
857 
858  moves.emplace_back(reachmap.begin()->second[0], reachmap.begin()->first);
859 
860  reachmap.clear();
861  // We're done.
862  return false;
863  }
864 
865  return result;
866 }
867 
869  treachmap& reachmap, tmoves& moves, std::size_t& village_count)
870 {
871 
872  bool result = false;
873  bool dispatched = true;
874  while(dispatched) {
875  dispatched = false;
876 
877  // build the reverse map
878  std::map<map_location /*village location*/,
879  std::vector<map_location /* units that can reach it*/>>reversemap;
880 
881  treachmap::const_iterator itor = reachmap.begin();
882  for(;itor != reachmap.end(); ++itor) {
883 
884  for(std::vector<map_location>::const_iterator
885  v_itor = itor->second.begin();
886  v_itor != itor->second.end(); ++v_itor) {
887 
888  reversemap[*v_itor].push_back(itor->first);
889 
890  }
891  }
892 
893  village_count = reversemap.size();
894 
895  itor = reversemap.begin();
896  while(itor != reversemap.end()) {
897  if(itor->second.size() == 1) {
898  // One unit can reach this village.
899  const map_location village = itor->first;
900  dispatched = true;
901  result = true;
902 
903  DBG_AI_TESTING_AI_DEFAULT << "Dispatched unit at " << itor->second[0] << " to village " << itor->first << '\n';
904  moves.emplace_back(itor->first, itor->second[0]);
905 
906  reachmap.erase(itor->second[0]);
907  remove_village(reachmap, moves, village);
908  // Get can go to some trouble to remove the unit from the other villages
909  // instead we abort this loop end do a full rebuild on the map.
910  break;
911  } else {
912  ++itor;
913  }
914  }
915  }
916 
917  return result;
918 }
919 
921  treachmap& reachmap, tmoves& moves, const map_location& village)
922 {
923  bool result = false;
924  treachmap::iterator itor = reachmap.begin();
925  while(itor != reachmap.end()) {
926  itor->second.erase(std::remove(itor->second.begin(), itor->second.end(), village), itor->second.end());
927  if(itor->second.empty()) {
928  result = true;
929  itor = remove_unit(reachmap, moves, itor);
930  } else {
931  ++itor;
932  }
933  }
934  return result;
935 }
936 
938  treachmap& reachmap, tmoves& moves, treachmap::iterator unit)
939 {
940  assert(unit->second.empty());
941 
942  if(unit->first == leader_loc_ && best_leader_loc_ != map_location::null_location()) {
943  DBG_AI_TESTING_AI_DEFAULT << "Dispatch leader at " << leader_loc_ << " closer to the keep at "
944  << best_leader_loc_ << '\n';
945 
946  moves.emplace_back(best_leader_loc_, leader_loc_);
947  }
948 
949  reachmap.erase(unit++);
950  return unit;
951 }
952 
954  treachmap& reachmap, tmoves& moves, const std::size_t village_count)
955 {
956  // ***** ***** Init and dispatch if every unit can reach every village.
957 
958  const std::size_t unit_count = reachmap.size();
959  // The maximum number of villages we can capture with the available units.
960  const std::size_t max_result = unit_count < village_count ? unit_count : village_count;
961 
962  assert(unit_count >= 2 && village_count >= 2);
963 
964  // Every unit can reach every village.
965  if(unit_count == 2 && village_count == 2) {
966  DBG_AI_TESTING_AI_DEFAULT << "Every unit can reach every village for 2 units, dispatch them.\n";
967  full_dispatch(reachmap, moves);
968  return;
969  }
970 
971  std::vector<map_location> units(unit_count);
972  std::vector<std::size_t> villages_per_unit(unit_count);
973  std::vector<map_location> villages;
974  std::vector<std::size_t> units_per_village(village_count);
975 
976  // We want to test the units, the ones who can reach the least
977  // villages first so this is our lookup map.
978  std::multimap<std::size_t /* villages_per_unit value*/,
979  std::size_t /*villages_per_unit index*/> unit_lookup;
980 
981  std::vector</*unit*/boost::dynamic_bitset</*village*/>> matrix(reachmap.size(), boost::dynamic_bitset<>(village_count));
982 
983  treachmap::const_iterator itor = reachmap.begin();
984  for(std::size_t u = 0; u < unit_count; ++u, ++itor) {
985  units[u] = itor->first;
986  villages_per_unit[u] = itor->second.size();
987  unit_lookup.emplace(villages_per_unit[u], u);
988 
989  assert(itor->second.size() >= 2);
990 
991  for(std::size_t v = 0; v < itor->second.size(); ++v) {
992 
993  std::size_t v_index;
994  // find the index of the v in the villages
995  std::vector<map_location>::const_iterator v_itor =
996  std::find(villages.begin(), villages.end(), itor->second[v]);
997  if(v_itor == villages.end()) {
998  v_index = villages.size(); // will be the last element after push_back.
999  villages.push_back(itor->second[v]);
1000  } else {
1001  v_index = v_itor - villages.begin();
1002  }
1003 
1004  units_per_village[v_index]++;
1005 
1006  matrix[u][v_index] = true;
1007  }
1008  }
1009  for(std::vector<std::size_t>::const_iterator upv_it = units_per_village.begin();
1010  upv_it != units_per_village.end(); ++upv_it) {
1011 
1012  assert(*upv_it >=2);
1013  }
1014 
1015  if(debug_) {
1016  // Print header
1017  std::cerr << "Reach matrix:\n\nvillage";
1018  std::size_t u, v;
1019  for(v = 0; v < village_count; ++v) {
1020  std::cerr << '\t' << villages[v];
1021  }
1022  std::cerr << "\ttotal\nunit\n";
1023 
1024  // Print data
1025  for(u = 0; u < unit_count; ++u) {
1026  std::cerr << units[u];
1027 
1028  for(v = 0; v < village_count; ++v) {
1029  std::cerr << '\t' << matrix[u][v];
1030  }
1031  std::cerr << "\t" << villages_per_unit[u] << '\n';
1032  }
1033 
1034  // Print footer
1035  std::cerr << "total";
1036  for(v = 0; v < village_count; ++v) {
1037  std::cerr << '\t' << units_per_village[v];
1038  }
1039  std::cerr << '\n';
1040  }
1041 
1042  // Test the special case, everybody can reach all villages
1043  const bool reach_all = ((village_count == unit_count)
1044  && (std::accumulate(villages_per_unit.begin(), villages_per_unit.end(), std::size_t())
1045  == (village_count * unit_count)));
1046 
1047  if(reach_all) {
1048  DBG_AI_TESTING_AI_DEFAULT << "Every unit can reach every village, dispatch them\n";
1049  full_dispatch(reachmap, moves);
1050  reachmap.clear();
1051  return;
1052  }
1053 
1054  // ***** ***** Find a square
1055  std::multimap<std::size_t /* villages_per_unit value*/, std::size_t /*villages_per_unit index*/>
1056  ::const_iterator src_itor = unit_lookup.begin();
1057 
1058  while(src_itor != unit_lookup.end() && src_itor->first == 2) {
1059 
1060  for(std::multimap<std::size_t, std::size_t>::const_iterator
1061  dst_itor = unit_lookup.begin();
1062  dst_itor != unit_lookup.end(); ++ dst_itor) {
1063 
1064  // avoid comparing us with ourselves.
1065  if(src_itor == dst_itor) {
1066  continue;
1067  }
1068 
1069  boost::dynamic_bitset<> result = matrix[src_itor->second] & matrix[dst_itor->second];
1070  std::size_t matched = result.count();
1071 
1072  // we found a solution, dispatch
1073  if(matched == 2) {
1074  // Collect data
1075  std::size_t first = result.find_first();
1076  std::size_t second = result.find_next(first);
1077 
1078  const map_location village1 = villages[first];
1079  const map_location village2 = villages[second];
1080 
1081  const bool perfect = (src_itor->first == 2 &&
1082  dst_itor->first == 2 &&
1083  units_per_village[first] == 2 &&
1084  units_per_village[second] == 2);
1085 
1086  // Dispatch
1087  DBG_AI_TESTING_AI_DEFAULT << "Found a square.\nDispatched unit at " << units[src_itor->second]
1088  << " to village " << village1 << '\n';
1089  moves.emplace_back(village1, units[src_itor->second]);
1090 
1091  DBG_AI_TESTING_AI_DEFAULT << "Dispatched unit at " << units[dst_itor->second]
1092  << " to village " << village2 << '\n';
1093  moves.emplace_back(village2, units[dst_itor->second]);
1094 
1095  // Remove the units
1096  reachmap.erase(units[src_itor->second]);
1097  reachmap.erase(units[dst_itor->second]);
1098 
1099  // Evaluate and start correct function.
1100  if(perfect) {
1101  // We did a perfect dispatch 2 units who could visit 2 villages.
1102  // This means we didn't change the assertion for this functions
1103  // so call ourselves recursively, and finish afterwards.
1104  DBG_AI_TESTING_AI_DEFAULT << "Perfect dispatch, do complex again.\n";
1105  dispatch_complex(reachmap, moves, village_count - 2);
1106  return;
1107  } else {
1108  // We did a not perfect dispatch but we did modify things
1109  // so restart dispatching.
1110  DBG_AI_TESTING_AI_DEFAULT << "NON Perfect dispatch, do dispatch again.\n";
1111  remove_village(reachmap, moves, village1);
1112  remove_village(reachmap, moves, village2);
1113  dispatch(reachmap, moves);
1114  return;
1115  }
1116  }
1117  }
1118 
1119  ++src_itor;
1120  }
1121 
1122  // ***** ***** Do all permutations.
1123  // Now walk through all possible permutations
1124  // - test whether the suggestion is possible
1125  // - does it result in max_villages
1126  // - dispatch and ready
1127  // - is it's result better as the last best
1128  // - store
1129  std::vector<std::pair<map_location, map_location>> best_result;
1130 
1131  // Bruteforcing all possible permutations can result in a slow game.
1132  // So there needs to be a balance between the best possible result and
1133  // not too slow. From the test (at the end of the file) a good number is
1134  // picked. In general we shouldn't reach this point too often if we do
1135  // there are a lot of villages which are unclaimed and a lot of units
1136  // to claim them.
1137  const std::size_t max_options = 8;
1138  if(unit_count >= max_options && village_count >= max_options) {
1139 
1140  DBG_AI_TESTING_AI_DEFAULT << "Too many units " << unit_count << " and villages "
1141  << village_count<<" found, evaluate only the first "
1142  << max_options << " options;\n";
1143 
1144  std::vector<std::size_t> perm (max_options, 0);
1145  for(std::size_t i =0; i < max_options; ++i) {
1146  perm[i] = i;
1147  }
1148  while(std::next_permutation(perm.begin(), perm.end())) {
1149 
1150  // Get result for current permutation.
1151  std::vector<std::pair<map_location,map_location>> result;
1152  for(std::size_t u = 0; u < max_options; ++u) {
1153  if(matrix[u][perm[u]]) {
1154  result.emplace_back(villages[perm[u]], units[u]);
1155 
1156  }
1157  }
1158  if(result.size() == max_result) {
1159  best_result.swap(result);
1160  break;
1161  }
1162 
1163  if(result.size() > best_result.size()) {
1164  best_result.swap(result);
1165  }
1166  }
1167  // End of loop no optimal found, assign the best
1168  moves.insert(moves.end(), best_result.begin(), best_result.end());
1169 
1170  // Clean up the reachmap for dispatched units.
1171  for(const auto& unit_village_pair : best_result) {
1172  reachmap.erase(unit_village_pair.second);
1173  }
1174 
1175  // Try to dispatch whatever is left
1176  dispatch(reachmap, moves);
1177  return;
1178 
1179  } else if(unit_count <= village_count) {
1180 
1181  DBG_AI_TESTING_AI_DEFAULT << "Unit major\n";
1182 
1183  std::vector<std::size_t> perm (unit_count, 0);
1184  for(std::size_t i =0; i < unit_count; ++i) {
1185  perm[i] = i;
1186  }
1187  while(std::next_permutation(perm.begin(), perm.end())) {
1188  // Get result for current permutation.
1189  std::vector<std::pair<map_location,map_location>> result;
1190  for(std::size_t u = 0; u < unit_count; ++u) {
1191  if(matrix[u][perm[u]]) {
1192  result.emplace_back(villages[perm[u]], units[u]);
1193 
1194  }
1195  }
1196  if(result.size() == max_result) {
1197  moves.insert(moves.end(), result.begin(), result.end());
1198  reachmap.clear();
1199  return;
1200  }
1201 
1202  if(result.size() > best_result.size()) {
1203  best_result.swap(result);
1204  }
1205  }
1206  // End of loop no optimal found, assign the best
1207  moves.insert(moves.end(), best_result.begin(), best_result.end());
1208 
1209  // clean up the reachmap we need to test whether the leader is still there
1210  // and if so remove him manually to get him dispatched.
1211  for(const auto& unit_village_pair : best_result) {
1212  reachmap.erase(unit_village_pair.second);
1213  }
1214  treachmap::iterator unit = reachmap.find(leader_loc_);
1215  if(unit != reachmap.end()) {
1216  unit->second.clear();
1217  remove_unit(reachmap, moves, unit);
1218  }
1219  reachmap.clear();
1220 
1221  } else {
1222 
1223  DBG_AI_TESTING_AI_DEFAULT << "Village major\n";
1224 
1225  std::vector<std::size_t> perm (village_count, 0);
1226  for(std::size_t i =0; i < village_count; ++i) {
1227  perm[i] = i;
1228  }
1229  while(std::next_permutation(perm.begin(), perm.end())) {
1230  // Get result for current permutation.
1231  std::vector<std::pair<map_location,map_location>> result;
1232  for(std::size_t v = 0; v < village_count; ++v) {
1233  if(matrix[perm[v]][v]) {
1234  result.emplace_back(villages[v], units[perm[v]]);
1235 
1236  }
1237  }
1238  if(result.size() == max_result) {
1239  moves.insert(moves.end(), result.begin(), result.end());
1240  reachmap.clear();
1241  return;
1242  }
1243 
1244  if(result.size() > best_result.size()) {
1245  best_result.swap(result);
1246  }
1247  }
1248  // End of loop no optimal found, assigne the best
1249  moves.insert(moves.end(), best_result.begin(), best_result.end());
1250 
1251  // clean up the reachmap we need to test whether the leader is still there
1252  // and if so remove him manually to get him dispatched.
1253  for(const auto& unit_village_pair : best_result) {
1254  reachmap.erase(unit_village_pair.second);
1255  }
1256  treachmap::iterator unit = reachmap.find(leader_loc_);
1257  if(unit != reachmap.end()) {
1258  unit->second.clear();
1259  remove_unit(reachmap, moves, unit);
1260  }
1261  reachmap.clear();
1262  }
1263 }
1264 
1266 {
1267  treachmap::const_iterator itor = reachmap.begin();
1268  for(std::size_t i = 0; i < reachmap.size(); ++i, ++itor) {
1269  DBG_AI_TESTING_AI_DEFAULT << "Dispatched unit at " << itor->first
1270  << " to village " << itor->second[i] << '\n';
1271  moves.emplace_back(itor->second[i], itor->first);
1272  }
1273 }
1274 
1276 {
1277  if(!debug_) {
1278  return;
1279  }
1280 
1281  for(treachmap::const_iterator itor =
1282  reachmap.begin(); itor != reachmap.end(); ++itor) {
1283 
1284  std::cerr << "Reachlist for unit at " << itor->first;
1285 
1286  if(itor->second.empty()) {
1287  std::cerr << "\tNone";
1288  }
1289 
1290  for(std::vector<map_location>::const_iterator
1291  v_itor = itor->second.begin();
1292  v_itor != itor->second.end(); ++v_itor) {
1293 
1294  std::cerr << '\t' << *v_itor;
1295  }
1296  std::cerr << '\n';
1297 
1298  }
1299 }
1300 
1301 //==============================================================
1302 
1304  : candidate_action(context,cfg),move_()
1305 {
1306 }
1307 
1309 {
1310 }
1311 
1313 {
1314  // Find units in need of healing.
1315  unit_map &units_ = resources::gameboard->units();
1316  unit_map::iterator u_it = units_.begin();
1317  for(; u_it != units_.end(); ++u_it) {
1318  unit &u = *u_it;
1319 
1320  if(u.can_recruit() && get_passive_leader()){
1321  continue;
1322  }
1323 
1324  // If the unit is on our side, has lost as many or more than
1325  // 1/2 round worth of healing, and doesn't regenerate itself,
1326  // then try to find a vacant village for it to rest in.
1327  if(u.side() == get_side() &&
1330  !u.get_ability_bool("regenerate"))
1331  {
1332  // Look for the village which is the least vulnerable to enemy attack.
1333  typedef std::multimap<map_location,map_location>::const_iterator Itor;
1334  std::pair<Itor,Itor> it = get_srcdst().equal_range(u_it->get_location());
1335  double best_vulnerability = 100000.0;
1336  // Make leader units more unlikely to move to vulnerable villages
1337  const double leader_penalty = (u.can_recruit()?2.0:1.0);
1338  Itor best_loc = it.second;
1339  while(it.first != it.second) {
1340  const map_location& dst = it.first->second;
1341  if (resources::gameboard->map().gives_healing(dst) && (units_.find(dst) == units_.end() || dst == u_it->get_location())) {
1342  const double vuln = power_projection(dst, get_enemy_dstsrc());
1343  DBG_AI_TESTING_AI_DEFAULT << "found village with vulnerability: " << vuln << "\n";
1344  if(vuln < best_vulnerability) {
1345  best_vulnerability = vuln;
1346  best_loc = it.first;
1347  DBG_AI_TESTING_AI_DEFAULT << "chose village " << dst << '\n';
1348  }
1349  }
1350 
1351  ++it.first;
1352  }
1353 
1354  // If we have found an eligible village,
1355  // and we can move there without expecting to get whacked next turn:
1356  if(best_loc != it.second && best_vulnerability*leader_penalty < u.hitpoints()) {
1357  move_ = check_move_action(best_loc->first,best_loc->second,true);
1358  if (move_->is_ok()) {
1359  return get_score();
1360  }
1361  }
1362  }
1363  }
1364 
1365  return BAD_SCORE;
1366 }
1367 
1369 {
1370  LOG_AI_TESTING_AI_DEFAULT << "moving unit to village for healing...\n";
1371  move_->execute();
1372  if (!move_->is_ok()){
1373  LOG_AI_TESTING_AI_DEFAULT << get_name() << "::execute not ok" << std::endl;
1374  }
1375 }
1376 
1377 //==============================================================
1378 
1380  : candidate_action(context,cfg), move_()
1381 {
1382 }
1383 
1385 {
1386 }
1387 
1389 {
1390 
1391 
1392  // Get versions of the move map that assume that all units are at full movement
1393  const unit_map& units_ = resources::gameboard->units();
1394 
1395  //unit_map::const_iterator leader = units_.find_leader(get_side());
1396  std::vector<unit_map::const_iterator> leaders = units_.find_leaders(get_side());
1397  std::map<map_location,pathfind::paths> dummy_possible_moves;
1398 
1399  move_map fullmove_srcdst;
1400  move_map fullmove_dstsrc;
1401  calculate_possible_moves(dummy_possible_moves, fullmove_srcdst, fullmove_dstsrc,
1402  false, true, &get_avoid());
1403 
1404  /*adjacent_loc_array_t leader_adj;
1405  if(leader != units_.end()) {
1406  get_adjacent_tiles(leader->get_location(), leader_adj.data());
1407  }*/
1408  //int leader_adj_count = 0;
1409  std::vector<map_location> leaders_adj_v;
1410  for (unit_map::const_iterator leader : leaders) {
1411  adjacent_loc_array_t tmp_leader_adj;
1412  get_adjacent_tiles(leader->get_location(), tmp_leader_adj.data());
1413  for (map_location &loc : tmp_leader_adj) {
1414  bool found = false;
1415  for (map_location &new_loc : leaders_adj_v) {
1416  if(new_loc == loc){
1417  found = true;
1418  break;
1419  }
1420  }
1421  if(!found){
1422  leaders_adj_v.push_back(loc);
1423  }
1424  }
1425  }
1426  //leader_adj_count = leaders_adj_v.size();
1427 
1428 
1429  for(unit_map::const_iterator i = units_.begin(); i != units_.end(); ++i) {
1430  if (i->side() == get_side() &&
1431  i->movement_left() == i->total_movement() &&
1432  //leaders.find(*i) == leaders.end() && //unit_map::const_iterator(i) != leader &&
1433  std::find(leaders.begin(), leaders.end(), i) == leaders.end() &&
1434  !i->incapacitated())
1435  {
1436  // This unit still has movement left, and is a candidate to retreat.
1437  // We see the amount of power of each side on the situation,
1438  // and decide whether it should retreat.
1439  if(should_retreat(i->get_location(), i, fullmove_srcdst, fullmove_dstsrc, get_caution())) {
1440 
1441  bool can_reach_leader = false;
1442 
1443  // Time to retreat. Look for the place where the power balance
1444  // is most in our favor.
1445  // If we can't find anywhere where we like the power balance,
1446  // just try to get to the best defensive hex.
1447  typedef move_map::const_iterator Itor;
1448  std::pair<Itor,Itor> itors = get_srcdst().equal_range(i->get_location());
1449  map_location best_pos, best_defensive(i->get_location());
1450 
1451  double best_rating = -1000.0;
1452  int best_defensive_rating = i->defense_modifier(resources::gameboard->map().get_terrain(i->get_location()))
1453  - (resources::gameboard->map().is_village(i->get_location()) ? 10 : 0);
1454  while(itors.first != itors.second) {
1455 
1456  //if(leader != units_.end() && std::count(leader_adj,
1457  // leader_adj + 6, itors.first->second)) {
1458  if(std::find(leaders_adj_v.begin(), leaders_adj_v.end(), itors.first->second) != leaders_adj_v.end()){
1459 
1460  can_reach_leader = true;
1461  break;
1462  }
1463 
1464  // We rate the power balance of a hex based on our power projection
1465  // compared to theirs, multiplying their power projection by their
1466  // chance to hit us on the hex we're planning to flee to.
1467  const map_location& hex = itors.first->second;
1468  const int defense = i->defense_modifier(resources::gameboard->map().get_terrain(hex));
1469  const double our_power = power_projection(hex,get_dstsrc());
1470  const double their_power = power_projection(hex,get_enemy_dstsrc()) * static_cast<double>(defense)/100.0;
1471  const double rating = our_power - their_power;
1472  if(rating > best_rating) {
1473  best_pos = hex;
1474  best_rating = rating;
1475  }
1476 
1477  // Give a bonus for getting to a village.
1478  const int modified_defense = defense - (resources::gameboard->map().is_village(hex) ? 10 : 0);
1479 
1480  if(modified_defense < best_defensive_rating) {
1481  best_defensive_rating = modified_defense;
1482  best_defensive = hex;
1483  }
1484 
1485  ++itors.first;
1486  }
1487 
1488  // If the unit is in range of its leader, it should
1489  // never retreat -- it has to defend the leader instead.
1490  if(can_reach_leader) {
1491  continue;
1492  }
1493 
1494  if(!best_pos.valid()) {
1495  best_pos = best_defensive;
1496  }
1497 
1498  if(best_pos.valid()) {
1499  move_ = check_move_action(i->get_location(), best_pos, true);
1500  if (move_->is_ok()) {
1501  return get_score();
1502  }
1503  }
1504  }
1505  }
1506  }
1507 
1508  return BAD_SCORE;
1509 }
1510 
1512 {
1513  move_->execute();
1514  if (!move_->is_ok()){
1515  LOG_AI_TESTING_AI_DEFAULT << get_name() << "::execute not ok" << std::endl;
1516  }
1517 }
1518 
1519 
1520 
1521 bool retreat_phase::should_retreat(const map_location& loc, const unit_map::const_iterator& un, const move_map &srcdst, const move_map &dstsrc, double caution)
1522 {
1523  const move_map &enemy_dstsrc = get_enemy_dstsrc();
1524 
1525  if(caution <= 0.0) {
1526  return false;
1527  }
1528 
1529  double optimal_terrain = best_defensive_position(un->get_location(), dstsrc,
1530  srcdst, enemy_dstsrc).chance_to_hit/100.0;
1531  const double proposed_terrain =
1532  un->defense_modifier(resources::gameboard->map().get_terrain(loc)) / 100.0;
1533 
1534  // The 'exposure' is the additional % chance to hit
1535  // this unit receives from being on a sub-optimal defensive terrain.
1536  const double exposure = proposed_terrain - optimal_terrain;
1537 
1538  const double our_power = power_projection(loc,dstsrc);
1539  const double their_power = power_projection(loc,enemy_dstsrc);
1540  return caution*their_power*(1.0+exposure) > our_power;
1541 }
1542 
1543 
1544 //==============================================================
1545 
1547  : candidate_action(context,cfg)
1548 {
1549 }
1550 
1551 
1553 {
1554 }
1555 
1557 {
1558  ERR_AI_TESTING_AI_DEFAULT << get_name() << ": evaluate - not yet implemented" << std::endl;
1559  return BAD_SCORE;
1560 }
1561 
1562 
1563 
1565 {
1566  ERR_AI_TESTING_AI_DEFAULT << get_name() << ": execute - not yet implemented" << std::endl;
1567 }
1568 
1569 //==============================================================
1570 
1572  :candidate_action(context, cfg)
1573 {
1574 }
1575 
1577 {
1578 }
1579 
1581 {
1583  return BAD_SCORE;
1584  }
1585  bool allied_leaders_available = false;
1586  for(team &tmp_team : resources::gameboard->teams()) {
1587  if(!current_team().is_enemy(tmp_team.side())){
1588  std::vector<unit_map::unit_iterator> allied_leaders = resources::gameboard->units().find_leaders(get_side());
1589  if (!allied_leaders.empty()){
1590  allied_leaders_available = true;
1591  break;
1592  }
1593  }
1594  }
1595  if(allied_leaders_available){
1596  return get_score();
1597  }
1598  return BAD_SCORE;
1599 }
1600 
1602 {
1603  //get all AI leaders
1604  std::vector<unit_map::unit_iterator> ai_leaders = resources::gameboard->units().find_leaders(get_side());
1605 
1606  //calculate all possible moves (AI + allies)
1607  typedef std::map<map_location, pathfind::paths> path_map;
1608  path_map possible_moves;
1609  move_map friends_srcdst, friends_dstsrc;
1610  calculate_moves(resources::gameboard->units(), possible_moves, friends_srcdst, friends_dstsrc, false, true);
1611 
1612  //check for each ai leader if he should move away from his keep
1613  for (unit_map::unit_iterator &ai_leader : ai_leaders) {
1614  if(!ai_leader.valid()) {
1615  //This can happen if wml killed or moved a leader during a movement events of another leader
1616  continue;
1617  }
1618  //only if leader is on a keep
1619  const map_location &keep = ai_leader->get_location();
1620  if ( !resources::gameboard->map().is_keep(keep) ) {
1621  continue;
1622  }
1623  map_location recruit_loc = pathfind::find_vacant_castle(*ai_leader);
1624  if(!resources::gameboard->map().on_board(recruit_loc)){
1625  continue;
1626  }
1627  bool friend_can_reach_keep = false;
1628 
1629  //for each leader, check if he's allied and can reach our keep
1630  for(path_map::const_iterator i = possible_moves.begin(); i != possible_moves.end(); ++i){
1631  const unit_map::const_iterator itor = resources::gameboard->units().find(i->first);
1632  assert(itor.valid());
1633  team &leader_team = resources::gameboard->get_team(itor->side());
1634  if(itor != resources::gameboard->units().end() && itor->can_recruit() && itor->side() != get_side() && (leader_team.total_income() + leader_team.gold() > leader_team.minimum_recruit_price())){
1635  pathfind::paths::dest_vect::const_iterator tokeep = i->second.destinations.find(keep);
1636  if(tokeep != i->second.destinations.end()){
1637  friend_can_reach_keep = true;
1638  break;
1639  }
1640  }
1641  }
1642  //if there's no allied leader who can reach the keep, check next ai leader
1643  if(friend_can_reach_keep){
1644  //determine the best place the ai leader can move to
1645  map_location best_move;
1646  int defense_modifier = 100;
1647  for(pathfind::paths::dest_vect::const_iterator i = possible_moves[keep].destinations.begin()
1648  ; i != possible_moves[keep].destinations.end()
1649  ; ++i){
1650 
1651  //calculate_moves() above uses max. moves -> need to check movement_left of leader here
1652  if(distance_between(i->curr, keep) <= 3
1653  && static_cast<int>(distance_between(i->curr, keep)) <= ai_leader->movement_left()){
1654 
1655  int tmp_def_mod = ai_leader->defense_modifier(resources::gameboard->map().get_terrain(i->curr));
1656  if(tmp_def_mod < defense_modifier){
1657  defense_modifier = tmp_def_mod;
1658  best_move = i->curr;
1659  }
1660  }
1661  }
1662  //only move if there's a place with a good defense
1663  if(defense_modifier < 100){
1664  move_result_ptr move = check_move_action(keep, best_move, true);
1665  if(move->is_ok()){
1666  move->execute();
1667  if (!move->is_ok()){
1668  LOG_AI_TESTING_AI_DEFAULT << get_name() << "::execute not ok" << std::endl;
1669  }else{
1670  ai_leader->set_goto(keep);
1671  }
1672  // This is needed for sides with multiple leaders, in case a WML event does something
1673  // or to account for a leader having previously been moved by this CA execution
1674  possible_moves.clear();
1675  calculate_moves(resources::gameboard->units(), possible_moves, friends_srcdst, friends_dstsrc, false, true);
1676  }else{
1677  LOG_AI_TESTING_AI_DEFAULT << get_name() << "::execute not ok" << std::endl;
1678  }
1679  }
1680  }
1681  ai_leader->remove_movement_ai();
1682  }
1683  // re-get the AI leaders, in case an event did something
1684  ai_leaders = resources::gameboard->units().find_leaders(get_side());
1685  for(unit_map::unit_iterator &leader : ai_leaders) {
1686  leader->remove_movement_ai();
1687  }
1688  //ERR_AI_TESTING_AI_DEFAULT << get_name() << ": evaluate - not yet implemented" << std::endl;
1689 }
1690 
1691 
1692 //==============================================================
1693 
1694 
1695 } //end of namespace testing_ai_default
1696 
1697 } //end of namespace ai
void remove()
Removes a tip.
Definition: tooltip.cpp:189
virtual void execute()
Execute the candidate action.
Definition: ca.cpp:221
virtual void execute()
Execute the candidate action.
Definition: ca.cpp:338
virtual attack_result_ptr check_attack_action(const map_location &attacker_loc, const map_location &defender_loc, int attacker_weapon) override
Definition: contexts.hpp:539
int h() const
Effective map height.
Definition: map.hpp:128
std::vector< unit_iterator > find_leaders(int side)
Definition: map.cpp:357
unit_iterator end()
Definition: map.hpp:415
move_result_ptr move_
Definition: ca.hpp:44
virtual const attacks_vector & get_attacks() const override
Definition: contexts.hpp:657
virtual const std::vector< team > & teams() const override
Definition: game_board.hpp:92
std::vector< std::pair< map_location, map_location > > tmoves
Definition: ca.hpp:133
std::shared_ptr< stopunit_result > stopunit_result_ptr
Definition: game_info.hpp:86
void get_adjacent_tiles(const map_location &a, map_location *res)
Function which, given a location, will place all adjacent locations in res.
Definition: location.cpp:517
virtual const unit_map & units() const override
Definition: game_board.hpp:114
virtual const map_location & nearest_keep(const map_location &loc) const override
Definition: contexts.hpp:919
This class represents a single unit of a specific type.
Definition: unit.hpp:99
void dispatch(treachmap &reachmap, tmoves &moves)
Dispatches all units to their best location.
Definition: ca.cpp:764
int movement_cost(const t_translation::terrain_code &terrain) const
Get the unit&#39;s movement cost on a particular terrain.
Definition: unit.hpp:1339
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
goto_phase(rca_context &context, const config &cfg)
Definition: ca.cpp:55
static manager & get_singleton()
Definition: manager.hpp:150
map_location best_leader_loc_
The best possible location for our leader if it can&#39;t reach a village.
Definition: ca.hpp:124
bool get_state(const std::string &state) const
Check if the unit is affected by a status effect.
Definition: unit.cpp:1310
virtual stopunit_result_ptr check_stopunit_action(const map_location &unit_location, bool remove_movement=true, bool remove_attacks=false) override
Definition: contexts.hpp:563
unit_iterator find_leader(int side)
Definition: map.cpp:329
void dump_reachmap(treachmap &reachmap)
Shows which villages every unit can reach (debug function).
Definition: ca.cpp:1275
Managing the AI-Game interaction - AI actions and their results.
int hitpoints() const
The current number of hitpoints this unit has.
Definition: unit.hpp:453
leader_shares_keep_phase(rca_context &context, const config &cfg)
Definition: ca.cpp:1571
map_location keep_loc_
Location of the keep the closest to our leader.
Definition: ca.hpp:118
virtual const move_map & get_srcdst() const override
Definition: contexts.hpp:827
virtual double evaluate()
Evaluate the candidate action, resetting the internal state of the action.
Definition: ca.cpp:162
std::shared_ptr< move_result > move_result_ptr
Definition: game_info.hpp:84
map_location target
Definition: contexts.hpp:85
virtual const gamemap & map() const override
Definition: game_board.hpp:109
dest_vect destinations
Definition: pathfind.hpp:99
unit_iterator begin()
Definition: map.hpp:405
The unit is poisoned - it loses health each turn.
Definition: unit.hpp:810
Composite AI stages.
virtual double evaluate()
Evaluate the candidate action, resetting the internal state of the action.
Definition: ca.cpp:1312
virtual double evaluate()
Evaluate the candidate action, resetting the internal state of the action.
Definition: ca.cpp:374
AI Support engine - creating specific ai components from config.
bool on_board(const map_location &loc) const
Tell if a location is on the map.
Definition: map.cpp:377
-file sdl_utils.hpp
std::shared_ptr< attack_result > attack_result_ptr
Definition: game_info.hpp:81
move_leader_to_keep_phase(rca_context &context, const config &cfg)
Definition: ca.cpp:363
retreat_phase(rca_context &context, const config &cfg)
Definition: ca.cpp:1379
virtual double evaluate()
Evaluate the candidate action, resetting the internal state of the action.
Definition: ca.cpp:528
#define ERR_AI_TESTING_AI_DEFAULT
Definition: ca.cpp:46
Default AI (Testing)
bool remove_village(treachmap &reachmap, tmoves &moves, const map_location &village)
Removes a village for all units, returns true if anything is deleted.
Definition: ca.cpp:920
virtual void execute()
Execute the candidate action.
Definition: ca.cpp:1601
game_data * gamedata
Definition: resources.cpp:22
virtual double evaluate()
Evaluate the candidate action, resetting the internal state of the action.
Definition: ca.cpp:1388
t_translation::terrain_code get_terrain(const map_location &loc) const
Looks up terrain at a particular location.
Definition: map.cpp:309
std::multimap< map_location, map_location > move_map
The standard way in which a map of possible moves is recorded.
Definition: game_info.hpp:42
std::map< map_location, pathfind::paths > moves_map
The standard way in which a map of possible movement routes to location is recorded.
Definition: game_info.hpp:45
int defense_modifier(const t_translation::terrain_code &terrain) const
The unit&#39;s defense on a given terrain.
Definition: unit.cpp:1596
const config & options()
Definition: game.cpp:568
This class stores all the data for a single &#39;side&#39; (in game nomenclature).
Definition: team.hpp:44
static lg::log_domain log_ai_testing_ai_default("ai/ca/testing_ai_default")
A small explanation about what&#39;s going on here: Each action has access to two game_info objects First...
Definition: actions.cpp:58
team & get_team(int i)
Definition: game_board.hpp:104
virtual double evaluate()
Evaluate the candidate action, resetting the internal state of the action.
Definition: ca.cpp:259
std::vector< map_location > steps
Definition: pathfind.hpp:134
bool should_retreat(const map_location &loc, const unit_map::const_iterator &un, const move_map &srcdst, const move_map &dstsrc, double caution)
Definition: ca.cpp:1521
virtual void execute()
Execute the candidate action.
Definition: ca.cpp:504
Structure which holds a single route between one location and another.
Definition: pathfind.hpp:131
void dispatch_complex(treachmap &reachmap, tmoves &moves, const std::size_t village_count)
Dispatches the units to a village after the simple dispatching failed.
Definition: ca.cpp:953
map_location curr
Definition: pathfind.hpp:87
const defensive_position & best_defensive_position(const map_location &unit, const move_map &dstsrc, const move_map &srcdst, const move_map &enemy_dstsrc) const override
Definition: contexts.hpp:607
bool valid() const
Definition: location.hpp:93
virtual double evaluate()
Evaluate the candidate action, resetting the internal state of the action.
Definition: ca.cpp:1556
virtual double get_leader_aggression() const override
Definition: contexts.hpp:742
game_board * gameboard
Definition: resources.cpp:20
boost::dynamic_bitset<> dynamic_bitset
virtual bool get_passive_leader() const override
Definition: contexts.hpp:767
Encapsulates the map of the game.
Definition: map.hpp:36
virtual bool get_passive_leader_shares_keep() const override
Definition: contexts.hpp:773
virtual double evaluate()
Evaluate the candidate action, resetting the internal state of the action.
Definition: ca.cpp:1580
virtual const move_map & get_enemy_dstsrc() const override
Definition: contexts.hpp:688
leader_control_phase(rca_context &context, const config &cfg)
Definition: ca.cpp:1546
Managing the AIs lifecycle - headers TODO: Refactor history handling and internal commands...
virtual const std::vector< std::string > get_recruitment_pattern() const override
Definition: contexts.hpp:809
std::size_t count(const map_location &loc) const
Definition: map.hpp:400
void modify_active_ai_for_side(ai::side_number side, const config &cfg)
Modifies AI parameters for active AI of the given side.
Definition: manager.cpp:662
std::array< map_location, 6 > adjacent_loc_array_t
Definition: location.hpp:170
logger & debug()
Definition: log.cpp:96
bool dont_log(const log_domain &domain) const
Definition: log.hpp:123
int move_cost
Movement cost for reaching the end of the route.
Definition: pathfind.hpp:136
#define DBG_AI_TESTING_AI_DEFAULT
Definition: ca.cpp:43
bool dispatch_village_simple(treachmap &reachmap, tmoves &moves, std::size_t &village_count)
Definition: ca.cpp:868
Encapsulates the map of the game.
Definition: location.hpp:42
map_location leader_loc_
Locaton of our leader.
Definition: ca.hpp:121
unit_iterator find(std::size_t id)
Definition: map.cpp:311
get_healing_phase(rca_context &context, const config &cfg)
Definition: ca.cpp:1303
bool get_ability_bool(const std::string &tag_name, const map_location &loc) const
Checks whether this unit currently possesses or is affected by a given ability.
Definition: abilities.cpp:143
bool debug_
debug log level for AI enabled?
Definition: ca.hpp:127
int w() const
Effective map width.
Definition: map.hpp:125
virtual const map_location & suitable_keep(const map_location &leader_location, const pathfind::paths &leader_paths) const override
get most suitable keep for leader - nearest free that can be reached in 1 turn, if none - return near...
Definition: contexts.hpp:956
std::size_t i
Definition: function.cpp:933
bool dispatch_unit_simple(treachmap &reachmap, tmoves &moves)
Dispatches all units who can reach one village.
Definition: ca.cpp:824
virtual const team & current_team() const override
Definition: contexts.hpp:524
int max_hitpoints() const
The max number of hitpoints this unit can have.
Definition: unit.hpp:459
double g
Definition: astarsearch.cpp:64
std::vector< std::pair< map_location, map_location > > movements
Definition: contexts.hpp:86
bool can_recruit() const
Whether this unit can recruit other units - ie, are they a leader unit.
Definition: unit.hpp:570
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:785
std::string id_
Definition: rca.hpp:128
#define LOG_AI_TESTING_AI_DEFAULT
Definition: ca.cpp:44
virtual void execute()
Execute the candidate action.
Definition: ca.cpp:540
virtual side_number get_side() const override
Get the side number.
Definition: contexts.hpp:465
virtual move_result_ptr check_move_action(const map_location &from, const map_location &to, bool remove_movement=true, bool unreach_is_ok=false) override
Definition: contexts.hpp:544
std::map< map_location, std::vector< map_location > > treachmap
Definition: ca.hpp:130
virtual bool get_leader_ignores_keep() const override
Definition: contexts.hpp:755
virtual std::string get_name() const
Get the name of the candidate action (useful for debug purposes)
Definition: rca.hpp:86
void get_villages(const move_map &dstsrc, const move_map &enemy_dstsrc, unit_map::const_iterator &leader)
Definition: ca.cpp:585
#define next(ls)
Definition: llex.cpp:32
void full_dispatch(treachmap &reachmap, tmoves &moves)
Dispatches all units to a village, every unit can reach every village.
Definition: ca.cpp:1265
treachmap::iterator remove_unit(treachmap &reachmap, tmoves &moves, treachmap::iterator unit)
Removes a unit which can&#39;t reach any village anymore.
Definition: ca.cpp:937
bool is_village(const map_location &loc) const
Definition: map.cpp:65
virtual const move_map & get_dstsrc() const override
Definition: contexts.hpp:682
std::size_t distance_between(const map_location &a, const map_location &b)
Function which gives the number of hexes between two tiles (i.e.
Definition: location.cpp:600
get_villages_phase(rca_context &context, const config &cfg)
Definition: ca.cpp:514
virtual double get_aggression() const override
Definition: contexts.hpp:626
virtual void execute()
Execute the candidate action.
Definition: ca.cpp:1564
virtual void calculate_possible_moves(std::map< map_location, pathfind::paths > &possible_moves, move_map &srcdst, move_map &dstsrc, bool enemy, bool assume_full_movement=false, const terrain_filter *remove_destinations=nullptr) const override
Definition: contexts.hpp:573
bool find(E event, F functor)
Tests whether an event handler is available.
map_location prev
Definition: astarsearch.cpp:65
const map_location & get_location() const
The current map location this unit is at.
Definition: unit.hpp:1256
bool contains(const map_location &) const
Definition: pathfind.cpp:520
Standard logging facilities (interface).
const teleport_map get_teleport_locations(const unit &u, const team &viewing_team, bool see_all, bool ignore_units, bool check_vision)
Definition: teleport.cpp:259
Object which contains all the possible locations a unit can move to, with associated best routes to t...
Definition: pathfind.hpp:70
static const map_location & null_location()
Definition: location.hpp:85
static const double BAD_SCORE
Definition: rca.hpp:31
Container associating units to locations.
Definition: map.hpp:99
virtual void calculate_moves(const unit_map &units, std::map< map_location, pathfind::paths > &possible_moves, move_map &srcdst, move_map &dstsrc, bool enemy, bool assume_full_movement=false, const terrain_filter *remove_destinations=nullptr, bool see_all=false) const override
Definition: contexts.hpp:581
int side() const
The side this unit belongs to.
Definition: unit.hpp:303
virtual const terrain_filter & get_avoid() const override
Definition: contexts.hpp:670
virtual double evaluate()
Evaluate the candidate action, resetting the internal state of the action.
Definition: ca.cpp:65
virtual void execute()
Execute the candidate action.
Definition: ca.cpp:1368
plain_route a_star_search(const map_location &src, const map_location &dst, double stop_at, const cost_calculator &calc, const std::size_t width, const std::size_t height, const teleport_map *teleports, bool border)
A config object defines a single node in a WML file, with access to child nodes.
Definition: config.hpp:92
virtual move_result_ptr execute_move_action(const map_location &from, const map_location &to, bool remove_movement=true, bool unreach_is_ok=false) override
Definition: contexts.hpp:1006
combat_phase(rca_context &context, const config &cfg)
Definition: ca.cpp:153
bool valid() const
Definition: map.hpp:276
virtual double get_caution() const override
Definition: contexts.hpp:676
static map_location::DIRECTION n
double get_score() const
Get the usual score of the candidate action without re-evaluation.
Definition: rca.cpp:72
virtual void execute()
Execute the candidate action.
Definition: ca.cpp:129
virtual void execute()
Execute the candidate action.
Definition: ca.cpp:1511
#define WRN_AI_TESTING_AI_DEFAULT
Definition: ca.cpp:45
This module contains various pathfinding functions and utilities.
void remove_goal(const std::string &id)
Definition: ca.cpp:352
virtual const moves_map & get_possible_moves() const override
Definition: contexts.hpp:779
std::string::const_iterator iterator
Definition: tokenizer.hpp:24
virtual config get_leader_goal() const override
Definition: contexts.hpp:749
bool empty() const
Definition: config.cpp:888
void find_villages(treachmap &reachmap, tmoves &moves, const std::multimap< map_location, map_location > &dstsrc, const std::multimap< map_location, map_location > &enemy_dstsrc)
Definition: ca.cpp:645
move_leader_to_goals_phase(rca_context &context, const config &cfg)
Definition: ca.cpp:250
candidate action framework
attack_analysis best_analysis_
Definition: ca.hpp:60