-
-
Notifications
You must be signed in to change notification settings - Fork 988
/
ca.cpp
2164 lines (1780 loc) · 65.4 KB
/
ca.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (C) 2009 - 2016 by Yurii Chernyi <terraninfo@terraninfo.net>
Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY.
See the COPYING file for more details.
*/
/**
* Default AI (Testing)
* @file
*/
#include "ca.hpp"
#include "ai/actions.hpp"
#include "ai/manager.hpp"
#include "ai/composite/engine.hpp"
#include "ai/composite/rca.hpp"
#include "ai/composite/stage.hpp"
#include "game_board.hpp"
#include "game_classification.hpp"
#include "game_data.hpp"
#include "log.hpp"
#include "map.hpp"
#include "resources.hpp"
#include "team.hpp"
#include "unit.hpp"
#include "pathfind/pathfind.hpp"
#include "pathfind/teleport.hpp"
#include <boost/foreach.hpp>
#include <numeric>
#include <SDL.h>
static lg::log_domain log_ai_testing_ai_default("ai/ca/testing_ai_default");
#define DBG_AI_TESTING_AI_DEFAULT LOG_STREAM(debug, log_ai_testing_ai_default)
#define LOG_AI_TESTING_AI_DEFAULT LOG_STREAM(info, log_ai_testing_ai_default)
#define WRN_AI_TESTING_AI_DEFAULT LOG_STREAM(warn, log_ai_testing_ai_default)
#define ERR_AI_TESTING_AI_DEFAULT LOG_STREAM(err, log_ai_testing_ai_default)
namespace ai {
namespace testing_ai_default {
//==============================================================
goto_phase::goto_phase( rca_context &context, const config &cfg )
: candidate_action(context,cfg)
, move_()
{
}
goto_phase::~goto_phase()
{
}
double goto_phase::evaluate()
{
// Execute goto-movements - first collect gotos in a list
std::vector<map_location> gotos;
unit_map &units_ = *resources::units;
const gamemap &map_ = resources::gameboard->map();
for(unit_map::iterator ui = units_.begin(); ui != units_.end(); ++ui) {
if (ui->get_goto() == ui->get_location()) {
ui->set_goto(map_location());
} else if (ui->side() == get_side() && map_.on_board(ui->get_goto())) {
gotos.push_back(ui->get_location());
}
}
for(std::vector<map_location>::const_iterator g = gotos.begin(); g != gotos.end(); ++g) {
unit_map::const_iterator ui = units_.find(*g);
// passive_leader: never moves or attacks
if(ui->can_recruit() && get_passive_leader() && !get_passive_leader_shares_keep()){
continue;//@todo: only bail out if goto is on keep
}
// end of passive_leader
const pathfind::shortest_path_calculator calc(*ui, current_team(), *resources::teams, resources::gameboard->map());
const pathfind::teleport_map allowed_teleports = pathfind::get_teleport_locations(*ui, current_team());
pathfind::plain_route route;
route = pathfind::a_star_search(ui->get_location(), ui->get_goto(), 10000.0, &calc, map_.w(), map_.h(), &allowed_teleports);
if (!route.steps.empty()){
move_ = check_move_action(ui->get_location(), route.steps.back(), true, true);
} else {
// there is no direct path (yet)
// go to the nearest hex instead.
// maybe a door will open later or something
int closest_distance = -1;
std::pair<map_location,map_location> closest_move;
for(move_map::const_iterator i = get_dstsrc().begin(); i != get_dstsrc().end(); ++i) {
if(i->second != ui->get_location()) {
continue;
}
int distance = distance_between(i->first,ui->get_goto());
if(closest_distance == -1 || distance < closest_distance) {
closest_distance = distance;
closest_move = *i;
}
}
if(closest_distance != -1) {
move_ = check_move_action(ui->get_location(), closest_move.first);
} else {
return BAD_SCORE;
}
}
if (move_->is_ok()) {
return get_score();
}
}
return BAD_SCORE;
}
void goto_phase::execute()
{
if (!move_) {
return;
}
move_->execute();
if (!move_->is_ok()){
LOG_AI_TESTING_AI_DEFAULT << get_name() << "::execute not ok" << std::endl;
}
}
//==============================================================
aspect_recruitment_phase::aspect_recruitment_phase( rca_context &context, const config &cfg )
: candidate_action(context,cfg)
{
}
aspect_recruitment_phase::~aspect_recruitment_phase()
{
}
double aspect_recruitment_phase::evaluate()
{
const unit_map::const_iterator leader = resources::units->find_leader(get_side());
if(leader == resources::units->end()) {
return BAD_SCORE;
}
if (!resources::gameboard->map().is_keep(leader->get_location())) {
return BAD_SCORE;
}
map_location recruit_loc = pathfind::find_vacant_castle(*leader);
if (!resources::gameboard->map().on_board(recruit_loc)) {
return BAD_SCORE;
}
//note that no gold check is done. This is intended, to speed up recruitment_phase::evaluate()
//so, after 1st failed recruit, this candidate action will be blacklisted for 1 turn.
return get_score();
}
void aspect_recruitment_phase::execute()
{
raise_user_interact();
stage_ptr r = get_recruitment(*this);
if (r) {
r->play_stage();
} else {
ERR_AI_TESTING_AI_DEFAULT << "no recruitment aspect - skipping recruitment" << std::endl;
}
}
//==============================================================
recruitment_phase::recruitment_phase( rca_context &context, const config &cfg )
: candidate_action(context,cfg)
, unit_movement_scores_()
, not_recommended_units_()
, unit_combat_scores_()
{
}
recruitment_phase::~recruitment_phase()
{
}
double recruitment_phase::evaluate()
{
const unit_map::const_iterator leader = resources::units->find_leader(get_side());
if(leader == resources::units->end()) {
return BAD_SCORE;
}
if (!resources::gameboard->map().is_keep(leader->get_location())) {
return BAD_SCORE;
}
std::set<map_location> checked_hexes;
checked_hexes.insert(leader->get_location());
if (count_free_hexes_in_castle(leader->get_location(), checked_hexes)==0) {
return BAD_SCORE;
}
//note that no gold check is done. This is intended, to speed up recruitment_phase::evaluate()
//so, after 1st failed recruit, this candidate action will be blacklisted for 1 turn.
return get_score();
}
void recruitment_phase::execute()
{
not_recommended_units_.clear();
unit_combat_scores_.clear();
unit_movement_scores_.clear();
const unit_map &units_ = *resources::units;
const gamemap &map_ = resources::gameboard->map();
const std::vector<team> &teams_ = *resources::teams;
map_location start_pos = units_.find_leader(get_side())->get_location();
raise_user_interact();
//analyze_potential_recruit_movements();
analyze_potential_recruit_combat();
std::vector<std::string> options = get_recruitment_pattern();
if (std::count(options.begin(), options.end(), "scout") > 0) {
size_t neutral_villages = 0;
// We recruit the initial allocation of scouts
// based on how many neutral villages there are
// that are closer to us than to other keeps.
const std::vector<map_location>& villages = map_.villages();
for(std::vector<map_location>::const_iterator v = villages.begin(); v != villages.end(); ++v) {
const int owner = resources::gameboard->village_owner(*v);
if(owner == -1) {
const size_t distance = distance_between(start_pos,*v);
bool closest = true;
for(std::vector<team>::const_iterator i = teams_.begin(); i != teams_.end(); ++i) {
const int index = i - teams_.begin() + 1;
const map_location& loc = map_.starting_position(index);
if(loc != start_pos && distance_between(loc,*v) < distance) {
closest = false;
break;
}
}
if(closest) {
++neutral_villages;
}
}
}
// The villages per scout is for a two-side battle,
// accounting for all neutral villages on the map.
// We only look at villages closer to us, so we halve it,
// making us get twice as many scouts.
const int villages_per_scout = get_villages_per_scout()/2;
// Get scouts depending on how many neutral villages there are.
int scouts_wanted = villages_per_scout > 0 ? neutral_villages/villages_per_scout : 0;
LOG_AI_TESTING_AI_DEFAULT << "scouts_wanted: " << neutral_villages << "/"
<< villages_per_scout << " = " << scouts_wanted << "\n";
std::map<std::string,int> unit_types;
for(unit_map::const_iterator u = units_.begin(); u != units_.end(); ++u) {
if (u->side() == get_side()) {
++unit_types[u->usage()];
}
}
LOG_AI_TESTING_AI_DEFAULT << "we have " << unit_types["scout"] << " scouts already and we want "
<< scouts_wanted << " in total\n";
while(unit_types["scout"] < scouts_wanted) {
if (!recruit_usage("scout")){
break;
}
++unit_types["scout"];
}
}
// If there is no recruitment_pattern use "" which makes us consider
// any unit available.
if (options.empty()) {
options.push_back("");
}
// Buy units as long as we have room and can afford it.
while (recruit_usage(options[rand()%options.size()])) {
//refresh the recruitment pattern - it can be changed by recruit_usage
options = get_recruitment_pattern();
if (options.empty()) {
options.push_back("");
}
}
}
bool recruitment_phase::recruit_usage(const std::string& usage)
{
raise_user_interact();
const int min_gold = 0;
log_scope2(log_ai_testing_ai_default, "recruiting troops");
LOG_AI_TESTING_AI_DEFAULT << "recruiting '" << usage << "'\n";
//make sure id, usage and cost are known for the coming evaluation of unit types
unit_types.build_all(unit_type::HELP_INDEXED);
std::vector<std::string> options;
bool found = false;
// Find an available unit that can be recruited,
// matches the desired usage type, and comes in under budget.
BOOST_FOREACH(const std::string &name, current_team().recruits())
{
const unit_type *ut = unit_types.find(name);
if (!ut) continue;
// If usage is empty consider any unit.
if (usage.empty() || ut->usage() == usage) {
LOG_AI_TESTING_AI_DEFAULT << name << " considered for " << usage << " recruitment\n";
found = true;
if (current_team().gold() - ut->cost() < min_gold) {
LOG_AI_TESTING_AI_DEFAULT << name << " rejected, cost too high (cost: " << ut->cost() << ", current gold: " << current_team().gold() <<", min_gold: " << min_gold << ")\n";
continue;
}
if (not_recommended_units_.count(name))
{
LOG_AI_TESTING_AI_DEFAULT << name << " rejected, bad terrain or combat\n";
continue;
}
LOG_AI_TESTING_AI_DEFAULT << "recommending '" << name << "'\n";
options.push_back(name);
}
}
// From the available options, choose one at random
if(options.empty() == false) {
const int option = rand()%options.size();
recruit_result_ptr recruit_result = execute_recruit_action(options[option]);
return recruit_result->is_ok();
}
if (found) {
LOG_AI_TESTING_AI_DEFAULT << "No available units to recruit that come under the price.\n";
} else if (usage != "") {
//FIXME: This message should be suppressed when WML author
//chooses the default recruitment pattern.
const std::string warning = "At difficulty level " +
resources::classification->difficulty + ", trying to recruit a:" +
usage + " but no unit of that type (usage=) is"
" available. Check the recruit and [ai]"
" recruitment_pattern keys for team '" +
current_team().current_player() + "' (" +
lexical_cast<std::string>(get_side()) + ")"
" against the usage key of the"
" units in question! Removing invalid"
" recruitment_pattern entry and continuing...\n";
WRN_AI_TESTING_AI_DEFAULT << warning;
// Uncommented until the recruitment limiting macro can be fixed to not trigger this warning.
//lg::wml_error << warning;
//@fixme
//return current_team_w().remove_recruitment_pattern_entry(usage);
return false;
}
return false;
}
int recruitment_phase::average_resistance_against(const unit_type& a, const unit_type& b) const
{
int weighting_sum = 0, defense = 0;
const std::map<t_translation::t_terrain, size_t>& terrain =
resources::gameboard->map().get_weighted_terrain_frequencies();
for (std::map<t_translation::t_terrain, size_t>::const_iterator j = terrain.begin(),
j_end = terrain.end(); j != j_end; ++j)
{
// Use only reachable tiles when computing the average defense.
if (a.movement_type().movement_cost(j->first) < movetype::UNREACHABLE) {
defense += a.movement_type().defense_modifier(j->first) * j->second;
weighting_sum += j->second;
}
}
if (weighting_sum == 0) {
// This unit can't move on this map, so just get the average weighted
// of all available terrains. This still is a kind of silly
// since the opponent probably can't recruit this unit and it's a static unit.
for (std::map<t_translation::t_terrain, size_t>::const_iterator jj = terrain.begin(),
jj_end = terrain.end(); jj != jj_end; ++jj)
{
defense += a.movement_type().defense_modifier(jj->first) * jj->second;
weighting_sum += jj->second;
}
}
if(weighting_sum != 0) {
defense /= weighting_sum;
} else {
ERR_AI_TESTING_AI_DEFAULT << "The weighting sum is 0 and is ignored." << std::endl;
}
LOG_AI_TESTING_AI_DEFAULT << "average defense of '" << a.id() << "': " << defense << "\n";
int sum = 0, weight_sum = 0;
// calculation of the average damage taken
bool steadfast = a.has_ability_by_id("steadfast");
bool poisonable = !a.musthave_status("unpoisonable");
const std::vector<attack_type>& attacks = b.attacks();
for (std::vector<attack_type>::const_iterator i = attacks.begin(),
i_end = attacks.end(); i != i_end; ++i)
{
int resistance = a.movement_type().resistance_against(*i);
// Apply steadfast resistance modifier.
if (steadfast && resistance < 100)
resistance = std::max<int>(resistance * 2 - 100, 50);
// Do not look for filters or values, simply assume 70% if CTH is customized.
int cth = i->get_special_bool("chance_to_hit", true) ? 70 : defense;
int weight = i->damage() * i->num_attacks();
// if cth == 0 the division will do 0/0 so don't execute this part
if (poisonable && cth != 0 && i->get_special_bool("poison", true)) {
// Compute the probability of not poisoning the unit.
int prob = 100;
for (int j = 0; j < i->num_attacks(); ++j)
prob = prob * (100 - cth);
// Assume poison works one turn.
weight += game_config::poison_amount * (100 - prob) / 100;
}
sum += cth * resistance * weight * weight; // average damage * weight
weight_sum += weight;
}
// normalize by HP
sum /= std::max<int>(1,std::min<int>(a.hitpoints(),1000)); // avoid values really out of range
// Catch division by zero here if the attacking unit
// has zero attacks and/or zero damage.
// If it has no attack at all, the ai shouldn't prefer
// that unit anyway.
if (weight_sum == 0) {
return sum;
}
return sum/weight_sum;
}
int recruitment_phase::compare_unit_types(const unit_type& a, const unit_type& b) const
{
const int a_effectiveness_vs_b = average_resistance_against(b,a);
const int b_effectiveness_vs_a = average_resistance_against(a,b);
LOG_AI_TESTING_AI_DEFAULT << "comparison of '" << a.id() << " vs " << b.id() << ": "
<< a_effectiveness_vs_b << " - " << b_effectiveness_vs_a << " = "
<< (a_effectiveness_vs_b - b_effectiveness_vs_a) << '\n';
return a_effectiveness_vs_b - b_effectiveness_vs_a;
}
void recruitment_phase::analyze_potential_recruit_combat()
{
unit_map &units_ = *resources::units;
if(unit_combat_scores_.empty() == false || get_recruitment_ignore_bad_combat()) {
return;
}
log_scope2(log_ai_testing_ai_default, "analyze_potential_recruit_combat()");
// Records the best combat analysis for each usage type.
std::map<std::string,int> best_usage;
const std::set<std::string>& recruits = current_team().recruits();
std::set<std::string>::const_iterator i;
for(i = recruits.begin(); i != recruits.end(); ++i) {
const unit_type *info = unit_types.find(*i);
if (!info || not_recommended_units_.count(*i)) {
continue;
}
int score = 0, weighting = 0;
for(unit_map::const_iterator j = units_.begin(); j != units_.end(); ++j) {
if (j->can_recruit() || !current_team().is_enemy(j->side())) {
continue;
}
unit const &un = *j;
int weight = un.cost() * un.hitpoints() / un.max_hitpoints();
weighting += weight;
score += compare_unit_types(*info, un.type()) * weight;
}
if(weighting != 0) {
score /= weighting;
}
LOG_AI_TESTING_AI_DEFAULT << "combat score of '" << *i << "': " << score << "\n";
unit_combat_scores_[*i] = score;
if (best_usage.count(info->usage()) == 0 ||
score > best_usage[info->usage()]) {
best_usage[info->usage()] = score;
}
}
// Recommend not to use units of a certain usage type
// if they have a score more than 600 below
// the best unit of that usage type.
for(i = recruits.begin(); i != recruits.end(); ++i) {
const unit_type *info = unit_types.find(*i);
if (!info || not_recommended_units_.count(*i)) {
continue;
}
if (unit_combat_scores_[*i] + 600 < best_usage[info->usage()]) {
LOG_AI_TESTING_AI_DEFAULT << "recommending not to use '" << *i << "' because of poor combat performance "
<< unit_combat_scores_[*i] << "/" << best_usage[info->usage()] << "\n";
not_recommended_units_.insert(*i);
}
}
}
//==============================================================
combat_phase::combat_phase( rca_context &context, const config &cfg )
: candidate_action(context,cfg),best_analysis_(),choice_rating_(-1000.0)
{
}
combat_phase::~combat_phase()
{
}
double combat_phase::evaluate()
{
std::vector<std::string> options = get_recruitment_pattern();
choice_rating_ = -1000.0;
int ticks = SDL_GetTicks();
const std::vector<attack_analysis> analysis = get_attacks(); //passive_leader: in aspect_attacks::analyze_targets()
int time_taken = SDL_GetTicks() - ticks;
LOG_AI_TESTING_AI_DEFAULT << "took " << time_taken << " ticks for " << analysis.size()
<< " positions. Analyzing...\n";
ticks = SDL_GetTicks();
const int max_sims = 50000;
int num_sims = analysis.empty() ? 0 : max_sims/analysis.size();
if(num_sims < 20)
num_sims = 20;
if(num_sims > 40)
num_sims = 40;
LOG_AI_TESTING_AI_DEFAULT << "simulations: " << num_sims << "\n";
const int max_positions = 30000;
const int skip_num = analysis.size()/max_positions;
std::vector<attack_analysis>::const_iterator choice_it = analysis.end();
for(std::vector<attack_analysis>::const_iterator it = analysis.begin();
it != analysis.end(); ++it) {
if(skip_num > 0 && ((it - analysis.begin())%skip_num) && it->movements.size() > 1)
continue;
const double rating = it->rating(get_aggression(),*this);
LOG_AI_TESTING_AI_DEFAULT << "attack option rated at " << rating << " ("
<< (it->uses_leader ? get_leader_aggression() : get_aggression()) << ")\n";
if(rating > choice_rating_) {
choice_it = it;
choice_rating_ = rating;
}
}
time_taken = SDL_GetTicks() - ticks;
LOG_AI_TESTING_AI_DEFAULT << "analysis took " << time_taken << " ticks\n";
// suokko tested the rating against current_team().caution()
// Bad mistake -- the AI became extremely reluctant to attack anything.
// Documenting this in case someone has this bright idea again...*don't*...
if(choice_rating_ > 0.0) {
best_analysis_ = *choice_it;
return get_score();
} else {
return BAD_SCORE;
}
}
void combat_phase::execute()
{
assert(choice_rating_ > 0.0);
map_location from = best_analysis_.movements[0].first;
map_location to = best_analysis_.movements[0].second;
map_location target_loc = best_analysis_.target;
if (from!=to) {
move_result_ptr move_res = execute_move_action(from,to,false);
if (!move_res->is_ok()) {
LOG_AI_TESTING_AI_DEFAULT << get_name() << "::execute not ok, move failed" << std::endl;
return;
}
}
attack_result_ptr attack_res = check_attack_action(to, target_loc, -1);
if (!attack_res->is_ok()) {
LOG_AI_TESTING_AI_DEFAULT << get_name() << "::execute not ok, attack cancelled" << std::endl;
} else {
attack_res->execute();
if (!attack_res->is_ok()) {
LOG_AI_TESTING_AI_DEFAULT << get_name() << "::execute not ok, attack failed" << std::endl;
}
}
}
//==============================================================
move_leader_to_goals_phase::move_leader_to_goals_phase( rca_context &context, const config &cfg )
: candidate_action(context,cfg), auto_remove_(), dst_(), id_(), move_()
{
}
move_leader_to_goals_phase::~move_leader_to_goals_phase()
{
}
double move_leader_to_goals_phase::evaluate()
{
const config &goal = get_leader_goal();
//passive leader can reach a goal
if (!goal) {
LOG_AI_TESTING_AI_DEFAULT << get_name() << "No goal found\n";
return BAD_SCORE;
}
if (goal.empty()) {
LOG_AI_TESTING_AI_DEFAULT << get_name() << "Empty goal found\n";
return BAD_SCORE;
}
double max_risk = goal["max_risk"].to_double(1 - get_caution());
auto_remove_ = goal["auto_remove"].to_bool();
dst_ = map_location(goal, resources::gamedata);
if (!dst_.valid()) {
ERR_AI_TESTING_AI_DEFAULT << "Invalid goal: "<<std::endl<<goal;
return BAD_SCORE;
}
const unit_map::iterator leader = resources::units->find_leader(get_side());
if (!leader.valid() || leader->incapacitated()) {
WRN_AI_TESTING_AI_DEFAULT << "Leader not found" << std::endl;
return BAD_SCORE;
}
id_ = goal["id"].str();
if (leader->get_location() == dst_) {
//goal already reached
if (auto_remove_ && !id_.empty()) {
remove_goal(id_);
} else {
move_ = check_move_action(leader->get_location(), leader->get_location(), !auto_remove_);//we do full moves if we don't want to remove goal
if (move_->is_ok()) {
return get_score();
} else {
return BAD_SCORE;
}
}
}
pathfind::shortest_path_calculator calc(*leader, current_team(), *resources::teams, resources::gameboard->map());
pathfind::plain_route route = a_star_search(leader->get_location(), dst_, 1000.0, &calc,
resources::gameboard->map().w(), resources::gameboard->map().h());
if(route.steps.empty()) {
LOG_AI_TESTING_AI_DEFAULT << "route empty";
return BAD_SCORE;
}
const pathfind::paths leader_paths(*leader, false, true, current_team());
std::map<map_location,pathfind::paths> possible_moves;
possible_moves.insert(std::pair<map_location,pathfind::paths>(leader->get_location(), leader_paths));
map_location loc;
BOOST_FOREACH(const map_location &l, route.steps)
{
if (leader_paths.destinations.contains(l) &&
power_projection(l, get_enemy_dstsrc()) < leader->hitpoints() * max_risk)
{
loc = l;
}
}
if(loc.valid()) {
move_ = check_move_action(leader->get_location(), loc, false);
if (move_->is_ok()) {
return get_score();
}
}
return BAD_SCORE;
}
void move_leader_to_goals_phase::execute()
{
move_->execute();
if (!move_->is_ok()){
LOG_AI_TESTING_AI_DEFAULT << get_name() << "::execute not ok" << std::endl;
}
if (move_->get_unit_location()==dst_) {
//goal already reached
if (auto_remove_ && !id_.empty()) {
remove_goal(id_);
}
}
}
void move_leader_to_goals_phase::remove_goal(const std::string &id)
{
config mod_ai;
mod_ai["side"] = get_side();
mod_ai["path"] = "aspect[leader_goal].facet["+id+"]";
mod_ai["action"] = "delete";
manager::modify_active_ai_for_side(get_side(),mod_ai);
}
//==============================================================
move_leader_to_keep_phase::move_leader_to_keep_phase( rca_context &context, const config &cfg )
: candidate_action(context,cfg),move_()
{
}
move_leader_to_keep_phase::~move_leader_to_keep_phase()
{
}
double move_leader_to_keep_phase::evaluate()
{
if (get_leader_ignores_keep()) {
return BAD_SCORE;
}
if (get_passive_leader() && !get_passive_leader_shares_keep()) {
return BAD_SCORE;
}
// 1. Collect all leaders in a list
// 2. Get the suitable_keep for each leader
// 3. Choose the leader with the nearest suitable_keep (and which still have moves)
// 4. If leader can reach this keep in 1 turn -> set move_ to there
// 5. If not -> Calculate the best move_ (use a-star search)
// 6. Save move_ for execution
// 1.
const unit_map &units_ = *resources::units;
const std::vector<unit_map::const_iterator> leaders = units_.find_leaders(get_side());
if (leaders.empty()) {
return BAD_SCORE;
}
// 2. + 3.
const unit* best_leader = NULL;
map_location best_keep;
int shortest_distance = 99999;
BOOST_FOREACH(const unit_map::const_iterator& leader, leaders) {
if (leader->incapacitated() || leader->movement_left() == 0) {
continue;
}
// Find where the leader can move
const ai::moves_map &possible_moves = get_possible_moves();
const ai::moves_map::const_iterator& p_it = possible_moves.find(leader->get_location());
if (p_it == possible_moves.end()) {
return BAD_SCORE;
}
const pathfind::paths leader_paths = p_it->second;
const map_location& keep = suitable_keep(leader->get_location(), leader_paths);
if (keep == map_location::null_location() || keep == leader->get_location()) {
continue;
}
const pathfind::shortest_path_calculator calc(*leader, current_team(), *resources::teams, resources::gameboard->map());
const pathfind::teleport_map allowed_teleports = pathfind::get_teleport_locations(*leader, current_team());
pathfind::plain_route route;
route = pathfind::a_star_search(leader->get_location(), keep, 10000.0, &calc, resources::gameboard->map().w(), resources::gameboard->map().h(), &allowed_teleports);
if (!route.steps.empty() || route.move_cost < shortest_distance) {
best_leader = &(*leader);
best_keep = keep;
shortest_distance = route.move_cost;
}
}
if (best_leader == NULL) {
return BAD_SCORE;
}
// 4.
const unit* leader = best_leader;
const map_location keep = best_keep;
const pathfind::paths leader_paths(*leader, false, true, current_team());
const pathfind::shortest_path_calculator calc(*leader, current_team(), *resources::teams, resources::gameboard->map());
const pathfind::teleport_map allowed_teleports = pathfind::get_teleport_locations(*leader, current_team());
if (leader_paths.destinations.contains(keep) && units_.count(keep) == 0) {
move_ = check_move_action(leader->get_location(), keep, false);
if (move_->is_ok()) {
return get_score();
}
}
// 5.
// The leader can't move to his keep, try to move to the closest location
// to the keep where there are no enemies in range.
// Make a map of the possible locations the leader can move to,
// ordered by the distance from the keep.
typedef std::multimap<int, map_location> ordered_locations;
ordered_locations moves_toward_keep;
pathfind::plain_route route;
route = pathfind::a_star_search(leader->get_location(), keep, 10000.0, &calc, resources::gameboard->map().w(), resources::gameboard->map().h(), &allowed_teleports);
// find next hop
map_location next_hop = map_location::null_location();
int next_hop_cost = 0;
BOOST_FOREACH(const map_location& step, route.steps) {
if (leader_paths.destinations.contains(step)) {
next_hop = step;
next_hop_cost += leader->movement_cost(resources::gameboard->map().get_terrain(step));
} else {
break;
}
}
if (next_hop == map_location::null_location()) {
return BAD_SCORE;
}
//define the next hop to have the lowest cost (0)
moves_toward_keep.insert(std::make_pair(0, next_hop));
BOOST_FOREACH(const pathfind::paths::step &dest, leader_paths.destinations) {
if (!units_.find(dest.curr).valid()) {
route = pathfind::a_star_search(dest.curr, next_hop, 10000.0, &calc,
resources::gameboard->map().w(), resources::gameboard->map().h(), &allowed_teleports);
if (route.move_cost < next_hop_cost) {
moves_toward_keep.insert(std::make_pair(route.move_cost, dest.curr));
}
}
}
// Find the first location which we can move to,
// without the threat of enemies.
BOOST_FOREACH(const ordered_locations::value_type& pair, moves_toward_keep) {
const map_location& loc = pair.second;
if (get_enemy_dstsrc().count(loc) == 0) {
move_ = check_move_action(leader->get_location(), loc, true);
if (move_->is_ok()) {
return get_score();
}
}
}
return BAD_SCORE;
}
void move_leader_to_keep_phase::execute()
{
move_->execute();
if (!move_->is_ok()) {
LOG_AI_TESTING_AI_DEFAULT << get_name() <<"::execute not ok" << std::endl;
}
}
//==============================================================
get_villages_phase::get_villages_phase( rca_context &context, const config &cfg )
: candidate_action(context,cfg)
, keep_loc_()
, leader_loc_()
, best_leader_loc_()
, debug_(false)
, moves_()
{
}
get_villages_phase::~get_villages_phase()
{
}
double get_villages_phase::evaluate()
{
moves_.clear();
unit_map::const_iterator leader = resources::units->find_leader(get_side());
get_villages(get_dstsrc(),get_enemy_dstsrc(),leader);
if (!moves_.empty()) {
return get_score();
}
return BAD_SCORE;
}
void get_villages_phase::execute()
{
unit_map &units_ = *resources::units;
unit_map::const_iterator leader = units_.find_leader(get_side());
// Move all the units to get villages, however move the leader last,
// so that the castle will be cleared if it wants to stop to recruit along the way.
std::pair<map_location,map_location> leader_move;
for(tmoves::const_iterator i = moves_.begin(); i != moves_.end(); ++i) {
if(leader != units_.end() && leader->get_location() == i->second) {
leader_move = *i;
} else {
if (resources::gameboard->find_visible_unit(i->first, current_team()) == units_.end()) {
move_result_ptr move_res = execute_move_action(i->second,i->first,true);
if (!move_res->is_ok()) {
return;
}
const map_location loc = move_res->get_unit_location();
leader = units_.find_leader(get_side());
const unit_map::const_iterator new_unit = units_.find(loc);
if (new_unit != units_.end() &&
power_projection(i->first, get_enemy_dstsrc()) >= new_unit->hitpoints() / 4)
{
LOG_AI_TESTING_AI_DEFAULT << "found support target... " << new_unit->get_location() << '\n';
//FIXME: suokko tweaked the constant 1.0 to the formula:
//25.0* current_team().caution() * power_projection(loc,enemy_dstsrc) / new_unit->second.hitpoints()
//Is this an improvement?
///@todo 1.7 check if this an improvement
//add_target(target(new_unit->first,1.0,target::SUPPORT));
}
}
}
}
if(leader_move.second.valid()) {
if((resources::gameboard->find_visible_unit(leader_move.first , current_team()) == units_.end())
&& resources::gameboard->map().is_village(leader_move.first)) {
move_result_ptr move_res = execute_move_action(leader_move.second,leader_move.first,true);
if (!move_res->is_ok()) {
return;
}
}
}
return;
}
void get_villages_phase::get_villages(
const move_map& dstsrc, const move_map& enemy_dstsrc,
unit_map::const_iterator &leader)
{
DBG_AI_TESTING_AI_DEFAULT << "deciding which villages we want...\n";
unit_map &units_ = *resources::units;
const int ticks = SDL_GetTicks();
best_leader_loc_ = map_location::null_location();
if(leader != units_.end()) {
keep_loc_ = nearest_keep(leader->get_location());
leader_loc_ = leader->get_location();
} else {
keep_loc_ = map_location::null_location();
leader_loc_ = map_location::null_location();
}
debug_ = !lg::debug().dont_log(log_ai_testing_ai_default);
// Find our units who can move.
treachmap reachmap;