-
-
Notifications
You must be signed in to change notification settings - Fork 993
/
ca.cpp
1692 lines (1390 loc) · 50.9 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 - 2018 by Yurii Chernyi <terraninfo@terraninfo.net>
Part of the Battle for Wesnoth Project https://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 "ai/default/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/map.hpp"
#include "resources.hpp"
#include "team.hpp"
#include "units/unit.hpp"
#include "pathfind/pathfind.hpp"
#include "pathfind/teleport.hpp"
#include <numeric>
#include <boost/dynamic_bitset.hpp>
#include <SDL_timer.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 ai_default_rca {
//==============================================================
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::gameboard->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::gameboard->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 {
continue;
}
}
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;
}
// In some situations, a theoretically possible path is blocked by allies,
// resulting in the unit not moving. In this case, we remove all remaining
// movement from the unit in order to prevent blacklisting of the CA.
if (!move_->is_gamestate_changed()){
LOG_AI_TESTING_AI_DEFAULT << get_name() << "::execute did not move unit; removing moves instead" << std::endl;
stopunit_result_ptr stopunit = check_stopunit_action(move_->get_unit_location(), true, false);
stopunit->execute();
}
}
//==============================================================
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::gameboard->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::gameboard->teams(), resources::gameboard->map());
const pathfind::teleport_map allowed_teleports = pathfind::get_teleport_locations(*leader, current_team());
pathfind::plain_route route = a_star_search(leader->get_location(), dst_, 1000.0, calc,
resources::gameboard->map().w(), resources::gameboard->map().h(), &allowed_teleports);
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.emplace(leader->get_location(), leader_paths);
map_location loc;
for (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::get_singleton().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::gameboard->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 = nullptr;
map_location best_keep;
int shortest_distance = 99999;
for (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::gameboard->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 == nullptr) {
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::gameboard->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;
for (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.emplace(0, next_hop);
for (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.emplace(route.move_cost, dest.curr);
}
}
}
// Find the first location which we can move to,
// without the threat of enemies.
for (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::gameboard->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::gameboard->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.0)
{
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::gameboard->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;
for(unit_map::const_iterator u_itor = units_.begin();
u_itor != units_.end(); ++u_itor) {
if(u_itor->can_recruit() && get_passive_leader()){
continue;
}
if(u_itor->side() == get_side() && u_itor->movement_left()) {
reachmap.emplace(u_itor->get_location(), std::vector<map_location>());
}
}
DBG_AI_TESTING_AI_DEFAULT << reachmap.size() << " units found who can try to capture a village.\n";
find_villages(reachmap, moves_, dstsrc, enemy_dstsrc);
treachmap::iterator itor = reachmap.begin();
while(itor != reachmap.end()) {
if(itor->second.empty()) {
itor = remove_unit(reachmap, moves_, itor);
} else {
++itor;
}
}
if(!reachmap.empty()) {
DBG_AI_TESTING_AI_DEFAULT << reachmap.size() << " units left after removing the ones who "
"can't reach a village, send the to the dispatcher.\n";
dump_reachmap(reachmap);
dispatch(reachmap, moves_);
} else {
DBG_AI_TESTING_AI_DEFAULT << "No more units left after removing the ones who can't reach a village.\n";
}
LOG_AI_TESTING_AI_DEFAULT << "Village assignment done: " << (SDL_GetTicks() - ticks)
<< " ms, resulted in " << moves_.size() << " units being dispatched.\n";
}
void get_villages_phase::find_villages(
treachmap& reachmap,
tmoves& moves,
const std::multimap<map_location,map_location>& dstsrc,
const std::multimap<map_location,map_location>& enemy_dstsrc)
{
std::map<map_location, double> vulnerability;
const bool passive_leader = get_passive_leader();
size_t min_distance = 100000;
const gamemap &map_ = resources::gameboard->map();
std::vector<team> &teams_ = resources::gameboard->teams();
// When a unit is dispatched we need to make sure we don't
// dispatch this unit a second time, so store them here.
std::vector<map_location> dispatched_units;
for(std::multimap<map_location, map_location>::const_iterator
j = dstsrc.begin();
j != dstsrc.end(); ++j) {
const map_location ¤t_loc = j->first;
if(j->second == leader_loc_) {
if(passive_leader) {
continue;
}
const size_t distance = distance_between(keep_loc_, current_loc);
if(distance < min_distance) {
min_distance = distance;
best_leader_loc_ = current_loc;
}
}
if(std::find(dispatched_units.begin(), dispatched_units.end(),
j->second) != dispatched_units.end()) {
continue;
}
if(map_.is_village(current_loc) == false) {
continue;
}
bool want_village = true, owned = false;
for(size_t n = 0; n != teams_.size(); ++n) {
owned = teams_[n].owns_village(current_loc);
if(owned && !current_team().is_enemy(n+1)) {
want_village = false;
}
if(owned) {
break;
}
}
if(want_village == false) {
continue;
}
// If it is a neutral village, and we have no leader,
// then the village is of no use to us, and we don't want it.
if(!owned && leader_loc_ == map_location::null_location()) {
continue;
}
double threat = 0.0;
const std::map<map_location,double>::const_iterator vuln = vulnerability.find(current_loc);
if(vuln != vulnerability.end()) {
threat = vuln->second;
} else {
threat = power_projection(current_loc,enemy_dstsrc);
vulnerability.emplace(current_loc, threat);
}
const unit_map::const_iterator u = resources::gameboard->units().find(j->second);
if (u == resources::gameboard->units().end() || u->get_state("guardian")) {
continue;
}
const unit &un = *u;
//FIXME: suokko turned this 2:1 to 1.5:1.0.
//and dropped the second term of the multiplication. Is that better?
//const double threat_multipler = (current_loc == leader_loc?2:1) * current_team().caution() * 10;
if(un.hitpoints() < (threat*2*un.defense_modifier(map_.get_terrain(current_loc)))/100) {
continue;
}
// If the next and previous destination differs from our current destination,
// we're the only one who can reach the village -> dispatch.
std::multimap<map_location, map_location>::const_iterator next = j;
++next; // j + 1 fails
const bool at_begin = (j == dstsrc.begin());
std::multimap<map_location, map_location>::const_iterator prev = j; //FIXME seems not to work
if(!at_begin) {
--prev;
}
#if 1
if((next == dstsrc.end() || next->first != current_loc)
&& (at_begin || prev->first != current_loc)) {
move_result_ptr move_check_res = check_move_action(j->second,j->first,true);
if (move_check_res->is_ok()) {
DBG_AI_TESTING_AI_DEFAULT << "Dispatched unit at " << j->second << " to village " << j->first << '\n';
moves.emplace_back(j->first, j->second);
}
reachmap.erase(j->second);
dispatched_units.push_back(j->second);
continue;
}
#endif
reachmap[j->second].push_back(current_loc);
}
DBG_AI_TESTING_AI_DEFAULT << moves.size() << " units already dispatched, "
<< reachmap.size() << " left to evaluate.\n";
}
void get_villages_phase::dispatch(treachmap& reachmap, tmoves& moves)
{
DBG_AI_TESTING_AI_DEFAULT << "Starting simple dispatch.\n";
// we now have a list with units with the villages they can reach.
// keep trying the following steps as long as one of them changes
// the state.
// 1. Dispatch units who can reach 1 village (if more units can reach that
// village only one can capture it, so use the first in the list.)
// 2. Villages which can only be reached by one unit get that unit dispatched
// to them.
size_t village_count = 0;
bool dispatched = true;
while(dispatched) {
dispatched = false;
if(dispatch_unit_simple(reachmap, moves)) {
dispatched = true;
} else {
if(reachmap.empty()) {
DBG_AI_TESTING_AI_DEFAULT << "dispatch_unit_simple() found a final solution.\n";
break;
} else {
DBG_AI_TESTING_AI_DEFAULT << "dispatch_unit_simple() couldn't dispatch more units.\n";
}
}
if(dispatch_village_simple(reachmap, moves, village_count)) {
dispatched = true;
} else {
if(reachmap.empty()) {
DBG_AI_TESTING_AI_DEFAULT << "dispatch_village_simple() found a final solution.\n";
break;
} else {
DBG_AI_TESTING_AI_DEFAULT << "dispatch_village_simple() couldn't dispatch more units.\n";
}
}
if(!reachmap.empty() && dispatched) {
DBG_AI_TESTING_AI_DEFAULT << reachmap.size() << " unit(s) left restarting simple dispatching.\n";
dump_reachmap(reachmap);
}
}
if(reachmap.empty()) {
DBG_AI_TESTING_AI_DEFAULT << "No units left after simple dispatcher.\n";
return;
}
DBG_AI_TESTING_AI_DEFAULT << reachmap.size() << " units left for complex dispatch with "
<< village_count << " villages left.\n";
dump_reachmap(reachmap);
dispatch_complex(reachmap, moves, village_count);
}
// Returns need further processing
// false Nothing has been modified or no units left
bool get_villages_phase::dispatch_unit_simple(treachmap& reachmap, tmoves& moves)
{
bool result = false;
treachmap::iterator itor = reachmap.begin();
while(itor != reachmap.end()) {
if(itor->second.size() == 1) {
const map_location village = itor->second[0];
result = true;
DBG_AI_TESTING_AI_DEFAULT << "Dispatched unit at " << itor->first << " to village " << village << '\n';
moves.emplace_back(village, itor->first);
reachmap.erase(itor++);
if(remove_village(reachmap, moves, village)) {
itor = reachmap.begin();
}
} else {
++itor;
}
}
// Test special cases.
if(reachmap.empty()) {
// We're done.
return false;
}
if(reachmap.size() == 1) {
// One unit left.
DBG_AI_TESTING_AI_DEFAULT << "Dispatched _last_ unit at " << reachmap.begin()->first
<< " to village " << reachmap.begin()->second[0] << '\n';
moves.emplace_back(reachmap.begin()->second[0], reachmap.begin()->first);
reachmap.clear();
// We're done.
return false;
}
return result;
}
bool get_villages_phase::dispatch_village_simple(
treachmap& reachmap, tmoves& moves, size_t& village_count)
{
bool result = false;
bool dispatched = true;
while(dispatched) {
dispatched = false;
// build the reverse map
std::map<map_location /*village location*/,
std::vector<map_location /* units that can reach it*/>>reversemap;
treachmap::const_iterator itor = reachmap.begin();
for(;itor != reachmap.end(); ++itor) {
for(std::vector<map_location>::const_iterator
v_itor = itor->second.begin();
v_itor != itor->second.end(); ++v_itor) {
reversemap[*v_itor].push_back(itor->first);
}
}
village_count = reversemap.size();
itor = reversemap.begin();
while(itor != reversemap.end()) {
if(itor->second.size() == 1) {
// One unit can reach this village.
const map_location village = itor->first;
dispatched = true;
result = true;
DBG_AI_TESTING_AI_DEFAULT << "Dispatched unit at " << itor->second[0] << " to village " << itor->first << '\n';
moves.emplace_back(itor->first, itor->second[0]);
reachmap.erase(itor->second[0]);
remove_village(reachmap, moves, village);
// Get can go to some trouble to remove the unit from the other villages
// instead we abort this loop end do a full rebuild on the map.
break;
} else {
++itor;
}
}
}
return result;
}
bool get_villages_phase::remove_village(
treachmap& reachmap, tmoves& moves, const map_location& village)
{
bool result = false;
treachmap::iterator itor = reachmap.begin();
while(itor != reachmap.end()) {
itor->second.erase(std::remove(itor->second.begin(), itor->second.end(), village), itor->second.end());
if(itor->second.empty()) {
result = true;
itor = remove_unit(reachmap, moves, itor);
} else {
++itor;
}
}
return result;
}
get_villages_phase::treachmap::iterator get_villages_phase::remove_unit(
treachmap& reachmap, tmoves& moves, treachmap::iterator unit)
{
assert(unit->second.empty());
if(unit->first == leader_loc_ && best_leader_loc_ != map_location::null_location()) {
DBG_AI_TESTING_AI_DEFAULT << "Dispatch leader at " << leader_loc_ << " closer to the keep at "
<< best_leader_loc_ << '\n';
moves.emplace_back(best_leader_loc_, leader_loc_);
}
reachmap.erase(unit++);
return unit;
}
void get_villages_phase::dispatch_complex(
treachmap& reachmap, tmoves& moves, const size_t village_count)
{
// ***** ***** Init and dispatch if every unit can reach every village.
const size_t unit_count = reachmap.size();
// The maximum number of villages we can capture with the available units.
const size_t max_result = unit_count < village_count ? unit_count : village_count;
assert(unit_count >= 2 && village_count >= 2);
// Every unit can reach every village.
if(unit_count == 2 && village_count == 2) {
DBG_AI_TESTING_AI_DEFAULT << "Every unit can reach every village for 2 units, dispatch them.\n";
full_dispatch(reachmap, moves);
return;
}
std::vector<map_location> units(unit_count);
std::vector<size_t> villages_per_unit(unit_count);
std::vector<map_location> villages;
std::vector<size_t> units_per_village(village_count);
// We want to test the units, the ones who can reach the least
// villages first so this is our lookup map.
std::multimap<size_t /* villages_per_unit value*/,
size_t /*villages_per_unit index*/> unit_lookup;
std::vector</*unit*/boost::dynamic_bitset</*village*/>> matrix(reachmap.size(), boost::dynamic_bitset<>(village_count));
treachmap::const_iterator itor = reachmap.begin();
for(size_t u = 0; u < unit_count; ++u, ++itor) {
units[u] = itor->first;
villages_per_unit[u] = itor->second.size();
unit_lookup.emplace(villages_per_unit[u], u);
assert(itor->second.size() >= 2);
for(size_t v = 0; v < itor->second.size(); ++v) {
size_t v_index;
// find the index of the v in the villages