-
-
Notifications
You must be signed in to change notification settings - Fork 988
/
recruitment.cpp
1866 lines (1685 loc) · 60.1 KB
/
recruitment.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) 2013 - 2018 by Felix Bauer
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.
*/
/**
* @file
* Recruitment Engine by flix
* See https://wiki.wesnoth.org/AI_Recruitment
*/
#include "ai/default/recruitment.hpp"
#include "ai/actions.hpp"
#include "ai/composite/rca.hpp"
#include "ai/manager.hpp"
#include "actions/attack.hpp"
#include "attack_prediction.hpp"
#include "display.hpp"
#include "filter_context.hpp"
#include "game_board.hpp"
#include "log.hpp"
#include "map/map.hpp"
#include "map/label.hpp"
#include "pathfind/pathfind.hpp"
#include "pathutils.hpp"
#include "random.hpp"
#include "resources.hpp"
#include "team.hpp"
#include "tod_manager.hpp"
#include "units/filter.hpp"
#include "units/map.hpp"
#include "units/types.hpp"
#include "units/unit.hpp"
#include "variable.hpp"
#include <cmath>
static lg::log_domain log_ai_recruitment("ai/recruitment");
#define LOG_AI_RECRUITMENT LOG_STREAM(info, log_ai_recruitment)
#define ERR_AI_RECRUITMENT LOG_STREAM(err, log_ai_recruitment)
namespace ai {
namespace default_recruitment {
namespace {
/**
* CONSTANTS
*/
// This is used for a income estimation. We'll calculate the estimated income of this much
// future turns and decide if we'd gain gold if we start to recruit no units anymore.
const static int SAVE_GOLD_FORECAST_TURNS = 5;
// When a team has less then this much units, consider recruit-list too.
const static unsigned int UNIT_THRESHOLD = 5;
// Defines the shape of the border-zone between enemies.
// Higher values mean more important hexes.
const static double MAP_BORDER_THICKNESS = 2.0;
const static double MAP_BORDER_WIDTH = 0.2;
// This parameter can be used to shift all important hexes in one directon.
// For example if our AI should act rather defensivly we may want to set
// this value to a negative number. Then the AI will more care about hexes
// nearer to the own units.
const static int MAP_OFFENSIVE_SHIFT = 0;
// When villages are this near to imprtant hexes they count as important.
const static int MAP_VILLAGE_NEARNESS_THRESHOLD = 3;
// Radius of area around important villages.
const static int MAP_VILLAGE_SURROUNDING = 1;
// Determines the power of a raw unit comparison
// A higher power means that *very good* units will be
// stronger favored compared to just *good* units.
const static double COMBAT_SCORE_POWER = 1.;
// A cache is used to store the simulation results.
// This value determines how much the average defenses of the important hexes can differ
// until the simulation will run again.
const static double COMBAT_CACHE_TOLERANCY = 0.5;
// The old recruitment CA usually recruited too many scouts.
// To prevent this we multiply the aspect village_per_scout with this constant.
const static double VILLAGE_PER_SCOUT_MULTIPLICATOR = 2.;
}
std::string data::to_string() const {
std::stringstream s;
s << "---------------Content of leader data---------------\n";
s << "For leader: " << leader->name() << "\n";
s << "ratio_score: " << ratio_score << "\n";
s << "recruit_count: " << recruit_count << "\n\n";
for (const score_map::value_type& entry : scores) {
s << std::setw(20) << entry.first <<
" score: " << std::setw(7) << entry.second << "\n";
}
s << "----------------------------------------------------\n";
return s.str();
}
recruitment::recruitment(rca_context& context, const config& cfg)
: candidate_action(context, cfg),
important_hexes_(),
important_terrain_(),
own_units_in_combat_counter_(0),
average_local_cost_(),
cheapest_unit_costs_(),
combat_cache_(),
recruit_situation_change_observer_(),
average_lawful_bonus_(0.0),
recruitment_instructions_(),
recruitment_instructions_turn_(-1),
own_units_count_(),
total_own_units_(0),
scouts_wanted_(0)
{
if (cfg["state"] == "save_gold") {
state_ = SAVE_GOLD;
} else if (cfg["state"] == "spend_all_gold") {
state_ = SPEND_ALL_GOLD;
} else {
state_ = NORMAL;
}
}
config recruitment::to_config() const {
config cfg = candidate_action::to_config();
if (state_ == SAVE_GOLD) {
cfg["state"] = "save_gold";
} else if (state_ == SPEND_ALL_GOLD) {
cfg["state"] = "spend_all_gold";
} else {
cfg["state"] = "normal";
}
return cfg;
}
double recruitment::evaluate() {
// Check if the recruitment list has changed.
// Then cheapest_unit_costs_ is not valid anymore.
if (recruit_situation_change_observer_.recruit_list_changed()) {
cheapest_unit_costs_.clear();
recruit_situation_change_observer_.set_recruit_list_changed(false);
}
// When evaluate() is called the first time this turn,
// we'll retrieve the recruitment-instruction aspect.
if (resources::tod_manager->turn() != recruitment_instructions_turn_) {
recruitment_instructions_ = get_recruitment_instructions();
integrate_recruitment_pattern_in_recruitment_instructions();
recruitment_instructions_turn_ = resources::tod_manager->turn();
LOG_AI_RECRUITMENT << "Recruitment-instructions updated:\n";
LOG_AI_RECRUITMENT << recruitment_instructions_ << "\n";
}
// Check if we have something to do.
const config* job = get_most_important_job();
if (!job) {
return BAD_SCORE;
}
const unit_map& units = resources::gameboard->units();
const std::vector<unit_map::const_iterator> leaders = units.find_leaders(get_side());
for (const unit_map::const_iterator& leader : leaders) {
if (leader == resources::gameboard->units().end()) {
return BAD_SCORE;
}
// Check Gold. But proceed if there is a unit with cost <= 0 (WML can do that)
int cheapest_unit_cost = get_cheapest_unit_cost_for_leader(leader);
if (current_team().gold() < cheapest_unit_cost && cheapest_unit_cost > 0) {
continue;
}
const map_location& loc = leader->get_location();
if (resources::gameboard->map().is_keep(loc) &&
pathfind::find_vacant_castle(*leader) != map_location::null_location()) {
return get_score();
}
}
return BAD_SCORE;
}
void recruitment::execute() {
LOG_AI_RECRUITMENT << "\n\n\n------------AI RECRUITMENT BEGIN---------------\n\n";
LOG_AI_RECRUITMENT << "TURN: " << resources::tod_manager->turn() <<
" SIDE: " << current_team().side() << "\n";
/*
* Check which leaders can recruit and collect them in leader_data.
*/
const unit_map& units = resources::gameboard->units();
const gamemap& map = resources::gameboard->map();
const std::vector<unit_map::const_iterator> leaders = units.find_leaders(get_side());
// This is the central datastructure with all score_tables in it.
std::vector<data> leader_data;
std::set<std::string> global_recruits;
for (const unit_map::const_iterator& leader : leaders) {
const map_location& keep = leader->get_location();
if (!resources::gameboard->map().is_keep(keep)) {
LOG_AI_RECRUITMENT << "Leader " << leader->name() << " is not on keep. \n";
continue;
}
if (pathfind::find_vacant_castle(*leader) == map_location::null_location()) {
LOG_AI_RECRUITMENT << "Leader " << leader->name() << " has no free hexes \n";
continue;
}
int cheapest_unit_cost = get_cheapest_unit_cost_for_leader(leader);
if (current_team().gold() < cheapest_unit_cost && cheapest_unit_cost > 0) {
LOG_AI_RECRUITMENT << "Leader " << leader->name() << " recruits are too expensive. \n";
continue;
}
// Leader can recruit.
data data(leader);
// Add team recruits.
for (const std::string& recruit : current_team().recruits()) {
if (!unit_types.find(recruit)) {
lg::wml_error() << "Unit-type \"" << recruit << "\" doesn't exist.\n";
}
data.recruits.insert(recruit);
data.scores[recruit] = 0.0;
global_recruits.insert(recruit);
}
// Add extra recruits.
for (const std::string& recruit : leader->recruits()) {
if (!unit_types.find(recruit)) {
lg::wml_error() << "Unit-type \"" << recruit << "\" doesn't exist.\n";
}
data.recruits.insert(recruit);
data.scores[recruit] = 0.0;
global_recruits.insert(recruit);
}
// Add recalls.
// Recalls are treated as recruits. While recruiting
// we'll check if we can do a recall instead of a recruitment.
for (const unit_const_ptr & recall : current_team().recall_list()) {
// Check if this leader is allowed to recall this unit.
const unit_filter ufilt( vconfig(leader->recall_filter()));
if (!ufilt(*recall, map_location::null_location())) {
continue;
}
const double recall_value = recruitment::recall_unit_value(recall);
if (recall_value < 0) {
continue; // Unit is not worth to get recalled.
}
data.recruits.insert(recall->type_id());
data.scores[recall->type_id()] = 0.0;
global_recruits.insert(recall->type_id());
}
// Check if leader is in danger. (If a enemies unit can attack the leader)
data.in_danger = power_projection(leader->get_location(), get_enemy_dstsrc()) > 0;
// If yes, set ratio_score very high, so this leader will get priority while recruiting.
if (data.in_danger) {
data.ratio_score = 50;
state_ = LEADER_IN_DANGER;
LOG_AI_RECRUITMENT << "Leader " << leader->name() << " is in danger.\n";
}
leader_data.push_back(data);
}
if (leader_data.empty()) {
LOG_AI_RECRUITMENT << "No leader available for recruiting. \n";
return; // This CA is going to be blacklisted for this turn.
}
if (global_recruits.empty()) {
LOG_AI_RECRUITMENT << "All leaders have empty recruitment lists. \n";
return; // This CA is going to be blacklisted for this turn.
}
/**
* Find important hexes and calculate other static things.
*/
update_important_hexes();
// Show "x" on important hexes if debug mode is activated AND
// the log domain "ai/recruitment" is used.
if (game_config::debug && !lg::info().dont_log(log_ai_recruitment)) {
show_important_hexes();
}
for (const map_location& hex : important_hexes_) {
++important_terrain_[map[hex]];
}
update_average_lawful_bonus();
update_own_units_count();
update_scouts_wanted();
/**
* Fill scores.
*/
do_combat_analysis(&leader_data);
LOG_AI_RECRUITMENT << "Scores before extra treatments:\n";
for (const data& data : leader_data) {
LOG_AI_RECRUITMENT << "\n" << data.to_string();
}
do_similarity_penalty(&leader_data);
do_randomness(&leader_data);
handle_recruitment_more(&leader_data);
LOG_AI_RECRUITMENT << "Scores after extra treatments:\n";
for (const data& data : leader_data) {
LOG_AI_RECRUITMENT << "\n" << data.to_string();
}
/**
* Do recruitment according to [recruit]-tags and scores.
* Note that the scores don't indicate the preferred mix to recruit but rather
* the preferred mix of all units. So already existing units are considered.
*/
action_result_ptr action_result;
config* job = nullptr;
do { // Recruitment loop
recruit_situation_change_observer_.reset_gamestate_changed();
// Check if we may want to save gold by not recruiting.
update_state();
int save_gold_turn = get_recruitment_save_gold()["active"].to_int(2); // From aspect.
int current_turn = resources::tod_manager->turn();
bool save_gold_active = save_gold_turn > 0 && save_gold_turn <= current_turn;
if (state_ == SAVE_GOLD && save_gold_active) {
break;
}
job = get_most_important_job();
if (!job) {
LOG_AI_RECRUITMENT << "All recruitment jobs (recruitment_instructions) done.\n";
break;
}
LOG_AI_RECRUITMENT << "Executing this job:\n" << *job << "\n";
data* best_leader_data = get_best_leader_from_ratio_scores(leader_data, job);
if (!best_leader_data) {
LOG_AI_RECRUITMENT << "Leader with job (recruitment_instruction) is not on keep.\n";
if (remove_job_if_no_blocker(job)) {
continue;
} else {
break;
}
}
LOG_AI_RECRUITMENT << "We want to have " << scouts_wanted_ << " more scouts.\n";
const std::string best_recruit = get_best_recruit_from_scores(*best_leader_data, job);
if (best_recruit.empty()) {
LOG_AI_RECRUITMENT << "Cannot fulfill recruitment-instruction.\n";
if (remove_job_if_no_blocker(job)) {
continue;
} else {
break;
}
}
LOG_AI_RECRUITMENT << "Best recruit is: " << best_recruit << "\n";
const std::string* recall_id = get_appropriate_recall(best_recruit, *best_leader_data);
if (recall_id) {
LOG_AI_RECRUITMENT << "Found appropriate recall with id: " << *recall_id << "\n";
action_result = execute_recall(*recall_id, *best_leader_data);
} else {
action_result = execute_recruit(best_recruit, *best_leader_data);
}
if (action_result->is_ok()) {
++own_units_count_[best_recruit];
++total_own_units_;
if (recruit_matches_type(best_recruit, "scout")) {
--scouts_wanted_;
}
// Update the current job.
if (!job->operator[]("total").to_bool(false)) {
job->operator[]("number") = job->operator[]("number").to_int(99999) - 1;
}
// Check if something changed in the recruitment list (WML can do that).
// If yes, just return/break. evaluate() and execute() will be called again.
if (recruit_situation_change_observer_.recruit_list_changed()) {
break;
}
// Check if the gamestate changed more than once.
// (Recruitment will trigger one gamestate change, WML could trigger more changes.)
// If yes, just return/break. evaluate() and execute() will be called again.
if (recruit_situation_change_observer_.gamestate_changed() > 1) {
break;
}
} else {
LOG_AI_RECRUITMENT << "Recruit result not ok.\n";
// We'll end up here if
// 1. We haven't enough gold,
// 2. There aren't any free hexes around leaders,
// 3. This leader can not recruit this type (this can happen after a recall)
}
} while((action_result && action_result->is_ok()) || !action_result);
// A action_result may be uninitialized if a job was removed. Continue then anyway.
// Recruiting is done now.
// Update state_ for next execution().
if (state_ == LEADER_IN_DANGER) {
state_ = NORMAL;
}
int status = (action_result) ? action_result->get_status() : -1;
bool no_gold = (status == recruit_result::E_NO_GOLD || status == recall_result::E_NO_GOLD);
if (state_ == SPEND_ALL_GOLD && no_gold) {
state_ = SAVE_GOLD;
}
if (job && no_gold) {
remove_job_if_no_blocker(job);
}
}
/**
* A helper function for execute().
*/
action_result_ptr recruitment::execute_recall(const std::string& id, data& leader_data) {
recall_result_ptr recall_result;
recall_result = check_recall_action(id, map_location::null_location(),
leader_data.leader->get_location());
if (recall_result->is_ok()) {
recall_result->execute();
++leader_data.recruit_count;
}
return recall_result;
}
/**
* A helper function for execute().
*/
action_result_ptr recruitment::execute_recruit(const std::string& type, data& leader_data) {
recruit_result_ptr recruit_result;
recruit_result = check_recruit_action(type, map_location::null_location(),
leader_data.leader->get_location());
if (recruit_result->is_ok()) {
recruit_result->execute();
LOG_AI_RECRUITMENT << "Recruited " << type << "\n";
++leader_data.recruit_count;
}
return recruit_result;
}
/**
* A helper function for execute().
* Checks if this unit type can be recalled.
* If yes, we calculate a estimated value in gold of the recall unit.
* If this value is less then the recall cost, we dismiss the unit.
* The unit with the highest value will be returned.
*/
double recruitment::recall_unit_value(const unit_const_ptr & recall_unit) const {
double average_cost_of_advanced_unit = 0;
int counter = 0;
for (const std::string& advancement : recall_unit->advances_to()) {
const unit_type* advancement_type = unit_types.find(advancement);
if (!advancement_type) {
continue;
}
average_cost_of_advanced_unit += advancement_type->cost();
++counter;
}
if (counter > 0) {
average_cost_of_advanced_unit /= counter;
} else {
// Unit don't have advancements. Use cost of unit itself.
average_cost_of_advanced_unit = recall_unit->cost();
}
double xp_quantity = static_cast<double>(recall_unit->experience()) /
recall_unit->max_experience();
double recall_value = recall_unit->cost() + xp_quantity * average_cost_of_advanced_unit;
int cost = current_team().recall_cost();
if (recall_unit->recall_cost() > -1) {
cost=recall_unit->recall_cost();
}
if (recall_value < cost) {
recall_value = -1; // Unit is not worth to get recalled.
}
return recall_value;
}
const std::string* recruitment::get_appropriate_recall(const std::string& type,
const data& leader_data) const {
const std::string* best_recall_id = nullptr;
double best_recall_value = -1;
for (const unit_const_ptr & recall_unit : current_team().recall_list()) {
if (type != recall_unit->type_id()) {
continue;
}
// Check if this leader is allowed to recall this unit.
const unit_filter ufilt(vconfig(leader_data.leader->recall_filter()));
if (!ufilt(*recall_unit, map_location::null_location())) {
LOG_AI_RECRUITMENT << "Refused recall because of filter: " << recall_unit->id() << "\n";
continue;
}
const double recall_value = recruitment::recall_unit_value(recall_unit);
if (recall_value > best_recall_value) {
best_recall_id = &recall_unit->id();
best_recall_value = recall_value;
}
}
return best_recall_id;
}
/**
* A helper function for execute().
* Decides according to the leaders ratio scores which leader should recruit.
*/
data* recruitment::get_best_leader_from_ratio_scores(std::vector<data>& leader_data,
const config* job) const {
assert(job);
// Find things for normalization.
int total_recruit_count = 0;
double ratio_score_sum = 0.0;
for (const data& data : leader_data) {
ratio_score_sum += data.ratio_score;
total_recruit_count += data.recruit_count;
}
assert(ratio_score_sum > 0.0);
// Shuffle leader_data to break ties randomly.
std::shuffle(leader_data.begin(), leader_data.end(), randomness::rng::default_instance());
// Find which leader should recruit according to ratio_scores.
data* best_leader_data = nullptr;
double biggest_difference = -99999.;
for (data& data : leader_data) {
if (!leader_matches_job(data, job)) {
continue;
}
double desired_ammount = data.ratio_score / ratio_score_sum * (total_recruit_count + 1);
double current_ammount = data.recruit_count;
double difference = desired_ammount - current_ammount;
if (difference > biggest_difference) {
biggest_difference = difference;
best_leader_data = &data;
}
}
return best_leader_data;
}
/**
* A helper function for execute().
* Counts own units and then decides what unit should be recruited so that the
* unit distribution approaches the given scores.
*/
const std::string recruitment::get_best_recruit_from_scores(const data& leader_data,
const config* job) {
assert(job);
std::string pattern_type = get_random_pattern_type_if_exists(leader_data, job);
if (!pattern_type.empty()) {
LOG_AI_RECRUITMENT << "Randomly chosen pattern_type: " << pattern_type << "\n";
}
std::string best_recruit = "";
double biggest_difference = -99999.;
for (const score_map::value_type& i : leader_data.get_normalized_scores()) {
const std::string& unit = i.first;
const double score = i.second;
if (!limit_ok(unit)) {
continue;
}
if (!pattern_type.empty()) {
if (!recruit_matches_type(unit, pattern_type)) {
continue;
}
} else {
if (!recruit_matches_job(unit, job)) {
continue;
}
}
double desired_ammount = score * (total_own_units_ + 1);
double current_ammount = own_units_count_[unit];
double difference = desired_ammount - current_ammount;
if (scouts_wanted_ > 0 && recruit_matches_type(unit, "scout")) {
difference += 1000.;
}
if (difference > biggest_difference) {
biggest_difference = difference;
best_recruit = unit;
}
}
return best_recruit;
}
/**
* For Map Analysis
* Computes from our cost map and the combined cost map of all enemies the important hexes.
*/
void recruitment::compare_cost_maps_and_update_important_hexes(
const pathfind::full_cost_map& my_cost_map,
const pathfind::full_cost_map& enemy_cost_map) {
const gamemap& map = resources::gameboard->map();
// First collect all hexes where the average costs are similar in important_hexes_candidates
// Then chose only those hexes where the average costs are relatively low.
// This is done to remove hexes to where the teams need a similar amount of moves but
// which are relatively far away comparing to other important hexes.
typedef std::map<map_location, double> border_cost_map;
border_cost_map important_hexes_candidates;
double smallest_border_movecost = 999999;
double biggest_border_movecost = 0;
for(int x = 0; x < map.w(); ++x) {
for (int y = 0; y < map.h(); ++y) {
double my_cost_average = my_cost_map.get_average_cost_at(x, y);
double enemy_cost_average = enemy_cost_map.get_average_cost_at(x, y);
if (my_cost_average == -1 || enemy_cost_average == -1) {
continue;
}
// We multiply the threshold MAP_BORDER_THICKNESS by the average_local_cost
// to favor high cost hexes (a bit).
if (std::abs(my_cost_average - MAP_OFFENSIVE_SHIFT - enemy_cost_average) <
MAP_BORDER_THICKNESS * average_local_cost_[map_location(x, y)]) {
double border_movecost = (my_cost_average + enemy_cost_average) / 2;
important_hexes_candidates[map_location(x, y)] = border_movecost;
if (border_movecost < smallest_border_movecost) {
smallest_border_movecost = border_movecost;
}
if (border_movecost > biggest_border_movecost) {
biggest_border_movecost = border_movecost;
}
}
} // for
} // for
double threshold = (biggest_border_movecost - smallest_border_movecost) *
MAP_BORDER_WIDTH + smallest_border_movecost;
for (const border_cost_map::value_type& candidate : important_hexes_candidates) {
if (candidate.second < threshold) {
important_hexes_.insert(candidate.first);
}
}
}
/**
* For Map Analysis.
* Calculates for a given unit the average defense on the map.
* (According to important_hexes_ / important_terrain_)
*/
double recruitment::get_average_defense(const std::string& u_type) const {
const unit_type* const u_info = unit_types.find(u_type);
if (!u_info) {
return 0.0;
}
long summed_defense = 0;
int total_terrains = 0;
for (const terrain_count_map::value_type& entry : important_terrain_) {
const t_translation::terrain_code& terrain = entry.first;
int count = entry.second;
int defense = 100 - u_info->movement_type().defense_modifier(terrain);
summed_defense += defense * count;
total_terrains += count;
}
double average_defense = (total_terrains == 0) ? 0.0 :
static_cast<double>(summed_defense) / total_terrains;
return average_defense;
}
/**
* For Map Analysis.
* Creates cost maps for a side. Each hex is map to
* a) the summed movecost and
* b) how many units can reach this hex
* for all units of side.
*/
const pathfind::full_cost_map recruitment::get_cost_map_of_side(int side) const {
const unit_map& units = resources::gameboard->units();
const team& team = resources::gameboard->get_team(side);
pathfind::full_cost_map cost_map(true, true, team, true, true);
// First add all existing units to cost_map.
unsigned int unit_count = 0;
for (const unit& unit : units) {
if (unit.side() != side || unit.can_recruit() ||
unit.incapacitated() || unit.total_movement() <= 0) {
continue;
}
++unit_count;
cost_map.add_unit(unit);
}
// If this side has not so many units yet, add unit_types with the leaders position as origin.
if (unit_count < UNIT_THRESHOLD) {
std::vector<unit_map::const_iterator> leaders = units.find_leaders(side);
for (const unit_map::const_iterator& leader : leaders) {
// First add team-recruits (it's fine when (team-)recruits are added multiple times).
for (const std::string& recruit : team.recruits()) {
cost_map.add_unit(leader->get_location(), unit_types.find(recruit), side);
}
// Next add extra-recruits.
for (const std::string& recruit : leader->recruits()) {
cost_map.add_unit(leader->get_location(), unit_types.find(recruit), side);
}
}
}
return cost_map;
}
/**
* For Map Analysis.
* Shows the important hexes for debugging purposes on the map. Only if debug is activated.
*/
void recruitment::show_important_hexes() const {
if (!game_config::debug) {
return;
}
display::get_singleton()->labels().clear_all();
for (const map_location& loc : important_hexes_) {
// Little hack: use map_location north from loc and make 2 linebreaks to center the "X".
display::get_singleton()->labels().set_label(loc.get_direction(map_location::NORTH), "\n\nX");
}
}
/**
* Calculates a average lawful bonus, so Combat Analysis will work
* better in caves and custom time of day cycles.
*/
void recruitment::update_average_lawful_bonus() {
int sum = 0;
int counter = 0;
for (const time_of_day& time : resources::tod_manager->times()) {
sum += time.lawful_bonus;
++counter;
}
if (counter > 0) {
average_lawful_bonus_ = std::round(static_cast<double>(sum) / counter);
}
}
/**
* For Map Analysis.
* Creates a map where each hex is mapped to the average cost of the terrain for our units.
*/
void recruitment::update_average_local_cost() {
average_local_cost_.clear();
const gamemap& map = resources::gameboard->map();
const team& team = resources::gameboard->get_team(get_side());
for(int x = 0; x < map.w(); ++x) {
for (int y = 0; y < map.h(); ++y) {
map_location loc(x, y);
int summed_cost = 0;
int count = 0;
for (const std::string& recruit : team.recruits()) {
const unit_type* const unit_type = unit_types.find(recruit);
if (!unit_type) {
continue;
}
int cost = unit_type->movement_type().get_movement().cost(map[loc]);
if (cost < 99) {
summed_cost += cost;
++count;
}
}
average_local_cost_[loc] = (count == 0) ? 0 : static_cast<double>(summed_cost) / count;
}
}
}
/**
* For Map Analysis.
* Creates a std::set of hexes where a fight will occur with high probability.
*/
void recruitment::update_important_hexes() {
important_hexes_.clear();
important_terrain_.clear();
own_units_in_combat_counter_ = 0;
update_average_local_cost();
const gamemap& map = resources::gameboard->map();
const unit_map& units = resources::gameboard->units();
// Mark battle areas as important
// This are locations where one of my units is adjacent
// to a enemies unit.
for (const unit& unit : units) {
if (unit.side() != get_side()) {
continue;
}
if (is_enemy_in_radius(unit.get_location(), 1)) {
// We found a enemy next to us. Mark our unit and all adjacent
// hexes as important.
std::vector<map_location> surrounding;
get_tiles_in_radius(unit.get_location(), 1, surrounding);
important_hexes_.insert(unit.get_location());
std::copy(surrounding.begin(), surrounding.end(),
std::inserter(important_hexes_, important_hexes_.begin()));
++own_units_in_combat_counter_;
}
}
// Mark area between me and enemies as important
// This is done by creating a cost_map for each team.
// A cost_map maps to each hex the average costs to reach this hex
// for all units of the team.
// The important hexes are those where my value on the cost map is
// similar to a enemies one.
const pathfind::full_cost_map my_cost_map = get_cost_map_of_side(get_side());
for (const team& team : resources::gameboard->teams()) {
if (current_team().is_enemy(team.side())) {
const pathfind::full_cost_map enemy_cost_map = get_cost_map_of_side(team.side());
compare_cost_maps_and_update_important_hexes(my_cost_map, enemy_cost_map);
}
}
// Mark 'near' villages and area around them as important
// To prevent a 'feedback' of important locations collect all
// important villages first and add them and their surroundings
// to important_hexes_ in a second step.
std::vector<map_location> important_villages;
for (const map_location& village : map.villages()) {
std::vector<map_location> surrounding;
get_tiles_in_radius(village, MAP_VILLAGE_NEARNESS_THRESHOLD, surrounding);
for (const map_location& hex : surrounding) {
if (important_hexes_.find(hex) != important_hexes_.end()) {
important_villages.push_back(village);
break;
}
}
}
for (const map_location& village : important_villages) {
important_hexes_.insert(village);
std::vector<map_location> surrounding;
get_tiles_in_radius(village, MAP_VILLAGE_SURROUNDING, surrounding);
for (const map_location& hex : surrounding) {
// only add hex if one of our units can reach the hex
if (map.on_board(hex) && my_cost_map.get_cost_at(hex.x, hex.y) != -1) {
important_hexes_.insert(hex);
}
}
}
}
/**
* For Combat Analysis.
* Calculates how good unit-type a is against unit type b.
* If the value is bigger then 0, a is better then b.
* If the value is 2.0 then unit-type a is twice as good as unit-type b.
* Since this function is called very often it uses a cache.
*/
double recruitment::compare_unit_types(const std::string& a, const std::string& b) {
const unit_type* const type_a = unit_types.find(a);
const unit_type* const type_b = unit_types.find(b);
if (!type_a || !type_b) {
ERR_AI_RECRUITMENT << "Couldn't find unit type: " << ((type_a) ? b : a) << "." << std::endl;
return 0.0;
}
double defense_a = get_average_defense(a);
double defense_b = get_average_defense(b);
const double* cache_value = get_cached_combat_value(a, b, defense_a, defense_b);
if (cache_value) {
return *cache_value;
}
double damage_to_a = 0.0;
double damage_to_b = 0.0;
// a attacks b
simulate_attack(type_a, type_b, defense_a, defense_b, &damage_to_a, &damage_to_b);
// b attacks a
simulate_attack(type_b, type_a, defense_b, defense_a, &damage_to_b, &damage_to_a);
int a_cost = (type_a->cost() > 0) ? type_a->cost() : 1;
int b_cost = (type_b->cost() > 0) ? type_b->cost() : 1;
int a_max_hp = (type_a->hitpoints() > 0) ? type_a->hitpoints() : 1;
int b_max_hp = (type_b->hitpoints() > 0) ? type_b->hitpoints() : 1;
double retval = 1.;
// There are rare cases where a unit deals 0 damage (eg. Elvish Lady).
// Then we just set the value to something reasonable.
if (damage_to_a <= 0 && damage_to_b <= 0) {
retval = 0.;
} else if (damage_to_a <= 0) {
retval = 2.;
} else if (damage_to_b <= 0) {
retval = -2.;
} else {
// Normal case
double value_of_a = damage_to_b / (b_max_hp * a_cost);
double value_of_b = damage_to_a / (a_max_hp * b_cost);
if (value_of_a > value_of_b) {
return value_of_a / value_of_b;
} else if (value_of_a < value_of_b) {
return -value_of_b / value_of_a;
} else {
return 0.;
}
}
// Insert in cache.
const cached_combat_value entry(defense_a, defense_b, retval);
std::set<cached_combat_value>& cache = combat_cache_[a][b];
cache.insert(entry);
return retval;
}
/**
* Combat Analysis.
* Main function.
* Compares all enemy units with all of our possible recruits and fills
* the scores.
*/
void recruitment::do_combat_analysis(std::vector<data>* leader_data) {
const unit_map& units = resources::gameboard->units();
// Collect all enemy units (and their hp) we want to take into account in enemy_units.
typedef std::vector<std::pair<std::string, int>> unit_hp_vector;
unit_hp_vector enemy_units;
for (const unit& unit : units) {
if (!current_team().is_enemy(unit.side()) || unit.incapacitated()) {
continue;
}
enemy_units.emplace_back(unit.type_id(), unit.hitpoints());
}
if (enemy_units.size() < UNIT_THRESHOLD) {
// Use also enemies recruitment lists and insert units into enemy_units.
for (const team& team : resources::gameboard->teams()) {
if (!current_team().is_enemy(team.side())) {
continue;
}
std::set<std::string> possible_recruits;
// Add team recruits.
possible_recruits.insert(team.recruits().begin(), team.recruits().end());
// Add extra recruits.
const std::vector<unit_map::const_iterator> leaders = units.find_leaders(team.side());
for (unit_map::const_iterator leader : leaders) {
possible_recruits.insert(leader->recruits().begin(), leader->recruits().end());
}
// Insert set in enemy_units.
for (const std::string& possible_recruit : possible_recruits) {
const unit_type* recruit_type = unit_types.find(possible_recruit);
if (recruit_type) {
int hp = recruit_type->hitpoints();
enemy_units.emplace_back(possible_recruit, hp);
}
}
}
}
for (data& leader : *leader_data) {
if (leader.recruits.empty()) {
continue;
}
typedef std::map<std::string, double> simple_score_map;
simple_score_map temp_scores;
for (const unit_hp_vector::value_type& entry : enemy_units) {
const std::string& enemy_unit = entry.first;
int enemy_unit_hp = entry.second;
for (const std::string& recruit : leader.recruits) {
double score = compare_unit_types(recruit, enemy_unit);
score *= enemy_unit_hp;
score = std::pow(score, COMBAT_SCORE_POWER);
temp_scores[recruit] += score;
}
}
if (temp_scores.empty()) {
return;
}
// Find things for normalization.