-
Notifications
You must be signed in to change notification settings - Fork 379
/
ProNonCombatMoveAi.java
2538 lines (2364 loc) · 108 KB
/
ProNonCombatMoveAi.java
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
package games.strategy.triplea.ai.pro;
import static games.strategy.triplea.ai.pro.util.ProUtils.summarizeUnits;
import static java.util.function.Predicate.not;
import com.google.common.base.Preconditions;
import games.strategy.engine.data.GameData;
import games.strategy.engine.data.GamePlayer;
import games.strategy.engine.data.MoveDescription;
import games.strategy.engine.data.Route;
import games.strategy.engine.data.Territory;
import games.strategy.engine.data.Unit;
import games.strategy.engine.data.UnitType;
import games.strategy.engine.data.util.BreadthFirstSearch;
import games.strategy.triplea.Properties;
import games.strategy.triplea.ai.pro.data.ProBattleResult;
import games.strategy.triplea.ai.pro.data.ProOtherMoveOptions;
import games.strategy.triplea.ai.pro.data.ProPlaceTerritory;
import games.strategy.triplea.ai.pro.data.ProPurchaseOption;
import games.strategy.triplea.ai.pro.data.ProPurchaseTerritory;
import games.strategy.triplea.ai.pro.data.ProTerritory;
import games.strategy.triplea.ai.pro.data.ProTerritoryManager;
import games.strategy.triplea.ai.pro.data.ProTransport;
import games.strategy.triplea.ai.pro.logging.ProLogger;
import games.strategy.triplea.ai.pro.util.ProBattleUtils;
import games.strategy.triplea.ai.pro.util.ProMatches;
import games.strategy.triplea.ai.pro.util.ProMoveUtils;
import games.strategy.triplea.ai.pro.util.ProOddsCalculator;
import games.strategy.triplea.ai.pro.util.ProPurchaseUtils;
import games.strategy.triplea.ai.pro.util.ProSortMoveOptionsUtils;
import games.strategy.triplea.ai.pro.util.ProTerritoryValueUtils;
import games.strategy.triplea.ai.pro.util.ProTransportUtils;
import games.strategy.triplea.ai.pro.util.ProUtils;
import games.strategy.triplea.attachments.TerritoryAttachment;
import games.strategy.triplea.delegate.AbstractMoveDelegate;
import games.strategy.triplea.delegate.GameStepPropertiesHelper;
import games.strategy.triplea.delegate.Matches;
import games.strategy.triplea.delegate.data.MoveValidationResult;
import games.strategy.triplea.delegate.move.validation.MoveValidator;
import games.strategy.triplea.delegate.remote.IMoveDelegate;
import games.strategy.triplea.util.TuvUtils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.commons.lang3.mutable.MutableObject;
import org.triplea.java.collections.CollectionUtils;
/** Pro non-combat move AI. */
class ProNonCombatMoveAi {
private final ProOddsCalculator calc;
private final ProData proData;
private GameData data;
private GamePlayer player;
private Map<Unit, Territory> unitTerritoryMap;
private ProTerritoryManager territoryManager;
ProNonCombatMoveAi(final AbstractProAi ai) {
calc = ai.getCalc();
proData = ai.getProData();
}
Map<Territory, ProTerritory> simulateNonCombatMove(final IMoveDelegate moveDel) {
return doNonCombatMove(null, null, moveDel);
}
Map<Territory, ProTerritory> doNonCombatMove(
final Map<Territory, ProTerritory> initialFactoryMoveMap,
final Map<Territory, ProPurchaseTerritory> purchaseTerritories,
final IMoveDelegate moveDel) {
ProLogger.info("Starting non-combat move phase");
// Current data at the start of non-combat move
data = proData.getData();
player = proData.getPlayer();
unitTerritoryMap = proData.getUnitTerritoryMap();
territoryManager = new ProTerritoryManager(calc, proData);
// Find the max number of units that can move to each allied territory
territoryManager.populateDefenseOptions(new ArrayList<>());
// Note: On maps that have a single move phase, this function may be called with this true.
boolean isCombatMove = GameStepPropertiesHelper.isCombatMove(data);
// Find number of units in each move territory that can't move and all infra units
findUnitsThatCantMove(purchaseTerritories, proData.getPurchaseOptions().getLandOptions());
final Map<Unit, Set<Territory>> infraUnitMoveMap = findInfraUnitsThatCanMove();
// Try to have one land unit in each territory that is bordering an enemy territory
final List<Territory> movedOneDefenderToTerritories =
moveOneDefenderToLandTerritoriesBorderingEnemy();
// Determine max enemy attack units and if territories can be held
territoryManager.populateEnemyAttackOptions(
movedOneDefenderToTerritories, territoryManager.getDefendTerritories());
determineIfMoveTerritoriesCanBeHeld();
// Prioritize territories to defend
Map<Territory, ProTerritory> factoryMoveMap = initialFactoryMoveMap;
final List<ProTerritory> prioritizedTerritories = prioritizeDefendOptions(factoryMoveMap);
// Determine which territories to defend and how many units each one needs
final Territory myCapital = proData.getMyCapital();
int enemyDistanceToMyCapital = Integer.MAX_VALUE;
if (myCapital != null) {
enemyDistanceToMyCapital =
ProUtils.getClosestEnemyLandTerritoryDistance(data, player, myCapital);
moveUnitsToDefendTerritories(isCombatMove, prioritizedTerritories, enemyDistanceToMyCapital);
}
// Copy data in case capital defense needs increased
final ProTerritoryManager territoryManagerCopy =
new ProTerritoryManager(calc, proData, territoryManager);
// Get list of territories that can't be held and find move value for each territory
final List<Territory> territoriesThatCantBeHeld = territoryManager.getCantHoldTerritories();
final Map<Territory, Double> territoryValueMap =
ProTerritoryValueUtils.findTerritoryValues(
proData,
player,
territoriesThatCantBeHeld,
List.of(),
new HashSet<>(territoryManager.getDefendTerritories()));
final Map<Territory, Double> seaTerritoryValueMap =
ProTerritoryValueUtils.findSeaTerritoryValues(
player, territoriesThatCantBeHeld, territoryManager.getDefendTerritories());
Map<Territory, ProTerritory> moveMap = territoryManager.getDefendOptions().getTerritoryMap();
// Use loop to ensure capital is protected after moves
if (myCapital != null) {
int defenseRange = -1;
while (true) {
// Add value to territories near capital if necessary
Predicate<Territory> canMove = ProMatches.territoryCanMoveLandUnits(player, isCombatMove);
for (final Territory t : territoryManager.getDefendTerritories()) {
double value = territoryValueMap.get(t);
final int distance = data.getMap().getDistance(myCapital, t, canMove);
if (distance >= 0 && distance <= defenseRange) {
value *= 10;
}
moveMap.get(t).setValue(value);
if (t.isWater()) {
moveMap.get(t).setSeaValue(seaTerritoryValueMap.get(t));
}
}
moveUnitsToBestTerritories(isCombatMove);
// Check if capital has local land superiority
ProLogger.info(
"Checking if capital has local land superiority with enemyDistanceToMyCapital="
+ enemyDistanceToMyCapital);
if (enemyDistanceToMyCapital >= 2
&& enemyDistanceToMyCapital <= 3
&& defenseRange == -1
&& !ProBattleUtils.territoryHasLocalLandSuperiorityAfterMoves(
proData, myCapital, enemyDistanceToMyCapital, player, moveMap)) {
defenseRange = enemyDistanceToMyCapital - 1;
territoryManager = territoryManagerCopy;
ProLogger.debug(
"Capital doesn't have local land superiority so setting defensive stance");
} else {
break;
}
}
} else {
moveUnitsToBestTerritories(isCombatMove);
}
// Determine where to move infra units
factoryMoveMap = moveInfraUnits(isCombatMove, factoryMoveMap, infraUnitMoveMap);
// Log a warning if any units not assigned to a territory (skip infrastructure for now)
for (final Unit u : territoryManager.getDefendOptions().getUnitMoveMap().keySet()) {
if (Matches.unitIsInfrastructure().negate().test(u)) {
ProLogger.warn(
player
+ ": "
+ unitTerritoryMap.get(u)
+ " has unmoved unit: "
+ u
+ " with options: "
+ territoryManager.getDefendOptions().getUnitMoveMap().get(u));
}
}
// Calculate move routes and perform moves
doMove(isCombatMove, moveMap, moveDel, data, player);
// Log results
ProLogger.info("Logging results");
logAttackMoves(prioritizedTerritories);
territoryManager = null;
return factoryMoveMap;
}
void doMove(
final boolean isCombatMove,
final Map<Territory, ProTerritory> moveMap,
final IMoveDelegate moveDel,
final GameData data,
final GamePlayer player) {
this.data = data;
this.player = player;
// Calculate move routes and perform moves
ProMoveUtils.doMove(
proData, ProMoveUtils.calculateMoveRoutes(proData, player, moveMap, isCombatMove), moveDel);
// Calculate amphib move routes and perform moves
ProMoveUtils.doMove(
proData,
ProMoveUtils.calculateAmphibRoutes(proData, player, moveMap, isCombatMove),
moveDel);
}
private void findUnitsThatCantMove(
final Map<Territory, ProPurchaseTerritory> purchaseTerritories,
final List<ProPurchaseOption> landPurchaseOptions) {
ProLogger.info("Find units that can't move");
Map<Territory, ProTerritory> moveMap = territoryManager.getDefendOptions().getTerritoryMap();
Map<Unit, Set<Territory>> unitMoveMap = territoryManager.getDefendOptions().getUnitMoveMap();
// Add all units that can't move (to be consumed, allied units, 0 move units, etc)
for (final Territory t : moveMap.keySet()) {
final ProTerritory proTerritory = moveMap.get(t);
Preconditions.checkState(proTerritory.getCantMoveUnits().isEmpty());
final Collection<Unit> cantMoveUnits =
t.getMatches(
ProMatches.unitCantBeMovedAndIsAlliedDefender(player, t)
.or(proData.getUnitsToBeConsumed()::contains));
proTerritory.addCantMoveUnits(cantMoveUnits);
}
// Add all units that only have 1 move option and can't be transported
for (final Iterator<Unit> it = unitMoveMap.keySet().iterator(); it.hasNext(); ) {
final Unit u = it.next();
final Set<Territory> territories = unitMoveMap.get(u);
if (territories.size() == 1) {
final Territory onlyTerritory = CollectionUtils.getAny(territories);
if (onlyTerritory.equals(unitTerritoryMap.get(u))
&& !canPotentiallyBeTransported(onlyTerritory)) {
moveMap.get(onlyTerritory).addCantMoveUnit(u);
it.remove();
}
}
}
// Check if purchase units are known yet
if (purchaseTerritories != null) {
// Add all units that will be purchased
for (final ProPurchaseTerritory ppt : purchaseTerritories.values()) {
for (final ProPlaceTerritory placeTerritory : ppt.getCanPlaceTerritories()) {
final Territory t = placeTerritory.getTerritory();
if (moveMap.get(t) != null) {
moveMap.get(t).addCantMoveUnits(placeTerritory.getPlaceUnits());
}
}
}
} else {
// Add max defenders that can be purchased to each territory
for (final Territory t : moveMap.keySet()) {
if (ProMatches.territoryHasNonMobileFactoryAndIsNotConqueredOwnedLand(player).test(t)) {
List<Unit> defendersToPurchase =
ProPurchaseUtils.findMaxPurchaseDefenders(proData, player, t, landPurchaseOptions);
moveMap.get(t).addCantMoveUnits(defendersToPurchase);
}
}
}
// Log can't move units per territory
for (final Territory t : moveMap.keySet()) {
if (!moveMap.get(t).getCantMoveUnits().isEmpty()) {
ProLogger.trace(t + " has units that can't move: " + moveMap.get(t).getCantMoveUnits());
}
}
}
private Map<Unit, Set<Territory>> findInfraUnitsThatCanMove() {
ProLogger.info("Find non-combat infra units that can move");
Map<Unit, Set<Territory>> unitMoveMap = territoryManager.getDefendOptions().getUnitMoveMap();
// Add all units that are infra
final Map<Unit, Set<Territory>> infraUnitMoveMap = new HashMap<>();
for (final Iterator<Unit> it = unitMoveMap.keySet().iterator(); it.hasNext(); ) {
final Unit u = it.next();
if (ProMatches.unitCanBeMovedAndIsOwned(player).test(u)
&& Matches.unitIsInfrastructure().test(u)) {
infraUnitMoveMap.put(u, unitMoveMap.get(u));
ProLogger.trace(u + " is infra unit with move options: " + unitMoveMap.get(u));
it.remove();
}
}
return infraUnitMoveMap;
}
private boolean canPotentiallyBeTransported(Territory unitTerritory) {
final List<ProTransport> transportMapList =
territoryManager.getDefendOptions().getTransportList();
for (final ProTransport pad : transportMapList) {
for (final Territory t : pad.getTransportMap().keySet()) {
if (pad.getTransportMap().get(t).contains(unitTerritory)) {
return true;
}
}
for (final Territory t : pad.getSeaTransportMap().keySet()) {
if (pad.getSeaTransportMap().get(t).contains(unitTerritory)) {
return true;
}
}
}
return false;
}
private List<Territory> moveOneDefenderToLandTerritoriesBorderingEnemy() {
ProLogger.info("Determine which territories to defend with one land unit");
Map<Territory, ProTerritory> moveMap = territoryManager.getDefendOptions().getTerritoryMap();
Map<Unit, Set<Territory>> unitMoveMap = territoryManager.getDefendOptions().getUnitMoveMap();
// Find land territories with no can't move units and adjacent to enemy land units
final List<Territory> territoriesToDefendWithOneUnit = new ArrayList<>();
final Predicate<Unit> alliedAndNotInfra = ProMatches.unitIsAlliedLandAndNotInfra(player);
final Predicate<Territory> hasNeighborOwnedByEnemyWithLandUnit =
ProMatches.territoryHasNeighborOwnedByAndHasLandUnit(
data.getMap(), ProUtils.getPotentialEnemyPlayers(player));
for (final Territory t : moveMap.keySet()) {
if (t.isWater()) {
continue;
}
final boolean hasAlliedLandUnits =
moveMap.get(t).getCantMoveUnits().stream().anyMatch(alliedAndNotInfra);
if (!hasAlliedLandUnits && hasNeighborOwnedByEnemyWithLandUnit.test(t)) {
territoriesToDefendWithOneUnit.add(t);
}
}
// Sort units by number of defend options and cost
final Map<Unit, Set<Territory>> sortedUnitMoveOptions =
ProSortMoveOptionsUtils.sortUnitMoveOptions(proData, unitMoveMap);
// Set unit with the fewest move options in each territory
for (final Unit unit : sortedUnitMoveOptions.keySet()) {
if (Matches.unitIsLand().test(unit)) {
for (final Territory t : sortedUnitMoveOptions.get(unit)) {
final int unitValue = proData.getUnitValue(unit.getType());
final int production = TerritoryAttachment.getProduction(t);
// Only defend territories that either already have units (avoid abandoning territories)
// or where unit value is less than production + 3 (avoid sacrificing expensive units to
// block)
if (territoriesToDefendWithOneUnit.contains(t)
&& (unitValue <= (production + 3)
|| Matches.territoryHasUnitsOwnedBy(player).test(t))) {
moveMap.get(t).addUnit(unit);
unitMoveMap.remove(unit);
territoriesToDefendWithOneUnit.remove(t);
ProLogger.debug(t + ", added one land unit: " + unit);
break;
}
}
if (territoriesToDefendWithOneUnit.isEmpty()) {
break;
}
}
}
// Only return territories that received a defender
return territoriesToDefendWithOneUnit;
}
private void determineIfMoveTerritoriesCanBeHeld() {
ProLogger.info("Find max enemy attackers and if territories can be held");
Map<Territory, ProTerritory> moveMap = territoryManager.getDefendOptions().getTerritoryMap();
final ProOtherMoveOptions enemyAttackOptions = territoryManager.getEnemyAttackOptions();
// Determine which territories can possibly be held
for (final Territory t : moveMap.keySet()) {
final ProTerritory patd = moveMap.get(t);
// Check if no enemy attackers
final ProTerritory enemyAttackMax = enemyAttackOptions.getMax(t);
if (enemyAttackMax == null) {
ProLogger.debug("Territory=" + t.getName() + ", CanHold=true since has no enemy attackers");
continue;
}
// Check if min defenders can hold it (not considering AA)
final Set<Unit> enemyAttackingUnits = new HashSet<>(enemyAttackMax.getMaxUnits());
enemyAttackingUnits.addAll(enemyAttackMax.getMaxAmphibUnits());
patd.setMaxEnemyUnits(enemyAttackingUnits);
patd.setMaxEnemyBombardUnits(enemyAttackMax.getMaxBombardUnits());
final List<Unit> minDefendingUnitsAndNotAa =
CollectionUtils.getMatches(
patd.getCantMoveUnits(), Matches.unitIsAaForAnything().negate());
final ProBattleResult minResult =
calc.calculateBattleResults(
proData,
t,
enemyAttackingUnits,
minDefendingUnitsAndNotAa,
enemyAttackMax.getMaxBombardUnits());
patd.setMinBattleResult(minResult);
if (minResult.getTuvSwing() <= 0 && !minDefendingUnitsAndNotAa.isEmpty()) {
ProLogger.debug(
"Territory="
+ t.getName()
+ ", CanHold=true"
+ ", MinDefenders="
+ minDefendingUnitsAndNotAa.size()
+ ", EnemyAttackers="
+ enemyAttackingUnits.size()
+ ", win%="
+ minResult.getWinPercentage()
+ ", EnemyTUVSwing="
+ minResult.getTuvSwing()
+ ", hasLandUnitRemaining="
+ minResult.isHasLandUnitRemaining());
continue;
}
// Check if max defenders can hold it (not considering AA)
final Set<Unit> defendingUnits = new HashSet<>(patd.getMaxUnits());
defendingUnits.addAll(patd.getMaxAmphibUnits());
defendingUnits.addAll(patd.getCantMoveUnits());
final List<Unit> defendingUnitsAndNotAa =
CollectionUtils.getMatches(defendingUnits, Matches.unitIsAaForAnything().negate());
final ProBattleResult result =
calc.calculateBattleResults(
proData,
t,
enemyAttackingUnits,
defendingUnitsAndNotAa,
enemyAttackOptions.getMax(t).getMaxBombardUnits());
int isFactory = 0;
if (ProMatches.territoryHasInfraFactoryAndIsLand().test(t)) {
isFactory = 1;
}
int isMyCapital = 0;
if (t.equals(proData.getMyCapital())) {
isMyCapital = 1;
}
final List<Unit> extraUnits = new ArrayList<>(defendingUnitsAndNotAa);
extraUnits.removeAll(minDefendingUnitsAndNotAa);
final double extraUnitValue = TuvUtils.getTuv(extraUnits, proData.getUnitValueMap());
final double holdValue = extraUnitValue / 8 * (1 + 0.5 * isFactory) * (1 + 2.0 * isMyCapital);
if (minDefendingUnitsAndNotAa.size() != defendingUnitsAndNotAa.size()
&& (result.getTuvSwing() - holdValue) < minResult.getTuvSwing()) {
ProLogger.debug(
"Territory="
+ t.getName()
+ ", CanHold=true"
+ ", MaxDefenders="
+ defendingUnitsAndNotAa.size()
+ ", EnemyAttackers="
+ enemyAttackingUnits.size()
+ ", minTUVSwing="
+ minResult.getTuvSwing()
+ ", win%="
+ result.getWinPercentage()
+ ", EnemyTUVSwing="
+ result.getTuvSwing()
+ ", hasLandUnitRemaining="
+ result.isHasLandUnitRemaining()
+ ", holdValue="
+ holdValue);
continue;
}
// Can't hold territory
patd.setCanHold(false);
ProLogger.debug(
"Can't hold Territory="
+ t.getName()
+ ", MaxDefenders="
+ defendingUnitsAndNotAa.size()
+ ", EnemyAttackers="
+ enemyAttackingUnits.size()
+ ", minTUVSwing="
+ minResult.getTuvSwing()
+ ", win%="
+ result.getWinPercentage()
+ ", EnemyTUVSwing="
+ result.getTuvSwing()
+ ", hasLandUnitRemaining="
+ result.isHasLandUnitRemaining()
+ ", holdValue="
+ holdValue);
}
}
private List<ProTerritory> prioritizeDefendOptions(
final Map<Territory, ProTerritory> factoryMoveMap) {
ProLogger.info("Prioritizing territories to try to defend");
Map<Territory, ProTerritory> moveMap = territoryManager.getDefendOptions().getTerritoryMap();
final ProOtherMoveOptions enemyAttackOptions = territoryManager.getEnemyAttackOptions();
// Calculate value of defending territory
for (final Territory t : moveMap.keySet()) {
// Determine if it is my capital or adjacent to my capital
final int isMyCapital = t.equals(proData.getMyCapital()) ? 1 : 0;
// Determine if it has a factory
int isFactory = 0;
if (ProMatches.territoryHasInfraFactoryAndIsLand().test(t)
|| (factoryMoveMap != null && factoryMoveMap.containsKey(t))) {
isFactory = 1;
}
// Determine production value and if it is an enemy capital
int production = 0;
int isEnemyOrAlliedCapital = 0;
final TerritoryAttachment ta = TerritoryAttachment.get(t);
if (ta != null) {
production = ta.getProduction();
if (ta.isCapital() && !t.equals(proData.getMyCapital())) {
isEnemyOrAlliedCapital = 1;
}
}
// Determine neighbor value
double neighborValue = 0;
if (!t.isWater()) {
final Set<Territory> landNeighbors =
data.getMap().getNeighbors(t, Matches.territoryIsLand());
for (final Territory neighbor : landNeighbors) {
double neighborProduction = TerritoryAttachment.getProduction(neighbor);
if (Matches.isTerritoryAllied(player).test(neighbor)) {
neighborProduction = 0.1 * neighborProduction;
}
neighborValue += neighborProduction;
}
}
// Determine defending unit value
final ProTerritory proTerritory = moveMap.get(t);
final int cantMoveUnitValue =
TuvUtils.getTuv(proTerritory.getCantMoveUnits(), proData.getUnitValueMap());
double unitOwnerMultiplier = 1;
if (proTerritory.getCantMoveUnits().stream().noneMatch(Matches.unitIsOwnedBy(player))) {
if (t.isWater()
&& proTerritory.getCantMoveUnits().stream()
.noneMatch(Matches.unitIsSeaTransportButNotCombatSeaTransport())) {
unitOwnerMultiplier = 0;
} else {
unitOwnerMultiplier = 0.5;
}
}
// Calculate defense value for prioritization
final double territoryValue =
unitOwnerMultiplier
* (2.0 * production
+ 10.0 * isFactory
+ 0.5 * cantMoveUnitValue
+ 0.5 * neighborValue)
* (1 + 10.0 * isMyCapital)
* (1 + 4.0 * isEnemyOrAlliedCapital);
proTerritory.setValue(territoryValue);
}
// Sort attack territories by value
final List<ProTerritory> prioritizedTerritories = new ArrayList<>(moveMap.values());
prioritizedTerritories.sort(Comparator.comparingDouble(ProTerritory::getValue).reversed());
// Remove territories that I'm not going to try to defend
for (final Iterator<ProTerritory> it = prioritizedTerritories.iterator(); it.hasNext(); ) {
final ProTerritory patd = it.next();
final Territory t = patd.getTerritory();
final boolean hasFactory = ProMatches.territoryHasInfraFactoryAndIsLand().test(t);
final ProBattleResult minResult = patd.getMinBattleResult();
final int cantMoveUnitValue =
TuvUtils.getTuv(patd.getCantMoveUnits(), proData.getUnitValueMap());
final List<Unit> maxEnemyUnits = patd.getMaxEnemyUnits();
final boolean isLandAndCanOnlyBeAttackedByAir =
!t.isWater()
&& !maxEnemyUnits.isEmpty()
&& maxEnemyUnits.stream().allMatch(Matches.unitIsAir());
final boolean isNotFactoryAndShouldHold =
!hasFactory && (minResult.getTuvSwing() <= 0 || !minResult.isHasLandUnitRemaining());
final boolean canAlreadyBeHeld =
minResult.getTuvSwing() <= 0
&& minResult.getWinPercentage() < (100 - proData.getWinPercentage());
final boolean isNotFactoryAndHasNoEnemyNeighbors =
!t.isWater()
&& !hasFactory
&& !ProMatches.territoryHasNeighborOwnedByAndHasLandUnit(
data.getMap(), ProUtils.getPotentialEnemyPlayers(player))
.test(t);
final boolean isNotFactoryAndOnlyAmphib =
!t.isWater()
&& !hasFactory
&& patd.getMaxUnits().stream().noneMatch(Matches.unitIsLand())
&& cantMoveUnitValue < 5;
if (!patd.isCanHold()
|| patd.getValue() <= 0
|| isLandAndCanOnlyBeAttackedByAir
|| isNotFactoryAndShouldHold
|| canAlreadyBeHeld
|| isNotFactoryAndHasNoEnemyNeighbors
|| isNotFactoryAndOnlyAmphib) {
final double tuvSwing = minResult.getTuvSwing();
final boolean hasRemainingLandUnit = minResult.isHasLandUnitRemaining();
ProLogger.debug(
"Removing territory="
+ t.getName()
+ ", value="
+ patd.getValue()
+ ", CanHold="
+ patd.isCanHold()
+ ", isLandAndCanOnlyBeAttackedByAir="
+ isLandAndCanOnlyBeAttackedByAir
+ ", isNotFactoryAndShouldHold="
+ isNotFactoryAndShouldHold
+ ", canAlreadyBeHeld="
+ canAlreadyBeHeld
+ ", isNotFactoryAndHasNoEnemyNeighbors="
+ isNotFactoryAndHasNoEnemyNeighbors
+ ", isNotFactoryAndOnlyAmphib="
+ isNotFactoryAndOnlyAmphib
+ ", tuvSwing="
+ tuvSwing
+ ", hasRemainingLandUnit="
+ hasRemainingLandUnit
+ ", maxEnemyUnits="
+ patd.getMaxEnemyUnits().size());
it.remove();
}
}
// Add best sea production territory for sea factories
List<Territory> seaFactories =
CollectionUtils.getMatches(
data.getMap().getTerritories(),
ProMatches.territoryHasFactoryAndIsNotConqueredOwnedLand(player));
seaFactories =
CollectionUtils.getMatches(
seaFactories, ProMatches.territoryHasInfraFactoryAndIsOwnedLandAdjacentToSea(player));
final Predicate<Territory> canMoveSeaUnits = ProMatches.territoryCanMoveSeaUnits(player, true);
final Set<Territory> territoriesToCheck = new HashSet<>(seaFactories);
for (final Territory t : seaFactories) {
territoriesToCheck.addAll(data.getMap().getNeighbors(t, canMoveSeaUnits));
}
final Map<Territory, Double> territoryValueMap =
ProTerritoryValueUtils.findTerritoryValues(
proData,
player,
territoryManager.getCantHoldTerritories(),
List.of(),
territoriesToCheck);
for (final Territory t : seaFactories) {
if (territoryValueMap.get(t) >= 1) {
continue;
}
final Set<Territory> neighbors = data.getMap().getNeighbors(t, canMoveSeaUnits);
double maxValue = 0;
Territory maxTerritory = null;
for (final Territory neighbor : neighbors) {
if (canHold(moveMap, neighbor) && territoryValueMap.get(neighbor) > maxValue) {
maxTerritory = neighbor;
maxValue = territoryValueMap.get(neighbor);
}
}
if (maxTerritory != null && enemyAttackOptions.getMax(maxTerritory) != null) {
boolean alreadyAdded = false;
for (final ProTerritory patd : prioritizedTerritories) {
if (patd.getTerritory().equals(maxTerritory)) {
alreadyAdded = true;
break;
}
}
if (!alreadyAdded) {
prioritizedTerritories.add(moveMap.get(maxTerritory));
}
}
}
// Log prioritized territories
for (final ProTerritory attackTerritoryData : prioritizedTerritories) {
ProLogger.debug(
"Value="
+ attackTerritoryData.getValue()
+ ", "
+ attackTerritoryData.getTerritory().getName());
}
return prioritizedTerritories;
}
private void moveUnitsToDefendTerritories(
final boolean isCombatMove,
final List<ProTerritory> prioritizedTerritories,
final int enemyDistance) {
ProLogger.info("Determine units to defend territories with");
if (prioritizedTerritories.isEmpty()) {
return;
}
final Map<Territory, ProTerritory> moveMap =
territoryManager.getDefendOptions().getTerritoryMap();
final Map<Unit, Set<Territory>> unitMoveMap =
territoryManager.getDefendOptions().getUnitMoveMap();
final Map<Unit, Set<Territory>> transportMoveMap =
territoryManager.getDefendOptions().getTransportMoveMap();
final List<ProTransport> transportMapList =
territoryManager.getDefendOptions().getTransportList();
// Assign units to territories by prioritization
int numToDefend = 1;
while (true) {
// Reset lists
for (final ProTerritory t : moveMap.values()) {
t.getTempUnits().clear();
t.getTempAmphibAttackMap().clear();
t.getTransportTerritoryMap().clear();
t.setBattleResult(null);
}
// Determine number of territories to defend
if (numToDefend <= 0) {
break;
}
final List<ProTerritory> territoriesToTryToDefend =
prioritizedTerritories.subList(0, numToDefend);
// Loop through all units and determine defend options
final Map<Unit, Set<Territory>> unitDefendOptions = new HashMap<>();
for (final Unit unit : unitMoveMap.keySet()) {
// Find number of move options
final Set<Territory> canDefendTerritories = new LinkedHashSet<>();
for (final ProTerritory attackTerritoryData : territoriesToTryToDefend) {
if (unitMoveMap.get(unit).contains(attackTerritoryData.getTerritory())) {
canDefendTerritories.add(attackTerritoryData.getTerritory());
}
}
unitDefendOptions.put(unit, canDefendTerritories);
}
// Sort units by number of defend options and cost
final Map<Unit, Set<Territory>> sortedUnitMoveOptions =
ProSortMoveOptionsUtils.sortUnitMoveOptions(proData, unitDefendOptions);
final List<Unit> addedUnits = new ArrayList<>();
// Set enough units in territories to have at least a chance of winning
for (final Unit unit : sortedUnitMoveOptions.keySet()) {
final boolean isAirUnit = unit.getUnitAttachment().getIsAir();
if (isAirUnit || Matches.unitIsCarrier().test(unit) || addedUnits.contains(unit)) {
continue; // skip air and carrier units
}
final TreeMap<Double, Territory> estimatesMap = new TreeMap<>();
for (final Territory t : sortedUnitMoveOptions.get(unit)) {
final ProTerritory proTerritory = moveMap.get(t);
final double estimate =
ProBattleUtils.estimateStrengthDifference(
t, proTerritory.getMaxEnemyUnits(), proTerritory.getEligibleDefenders(player));
estimatesMap.put(estimate, t);
}
if (!estimatesMap.isEmpty() && estimatesMap.lastKey() > 60) {
final Territory minWinTerritory = estimatesMap.lastEntry().getValue();
final List<Unit> unitsToAdd = ProTransportUtils.getUnitsToAdd(proData, unit, moveMap);
moveMap.get(minWinTerritory).addTempUnits(unitsToAdd);
addedUnits.addAll(unitsToAdd);
}
}
sortedUnitMoveOptions.keySet().removeAll(addedUnits);
// Set non-air units in territories
for (final Unit unit : sortedUnitMoveOptions.keySet()) {
if (Matches.unitCanLandOnCarrier().test(unit) || addedUnits.contains(unit)) {
continue;
}
Territory maxWinTerritory = null;
double maxWinPercentage = -1;
for (final Territory t : sortedUnitMoveOptions.get(unit)) {
final ProTerritory proTerritory = moveMap.get(t);
proTerritory.setBattleResultIfNull(
() ->
calc.estimateDefendBattleResults(
proData, proTerritory, proTerritory.getEligibleDefenders(player)));
final ProBattleResult result = proTerritory.getBattleResult();
final boolean hasFactory = ProMatches.territoryHasInfraFactoryAndIsLand().test(t);
if (result.getWinPercentage() > maxWinPercentage
&& ((t.equals(proData.getMyCapital())
&& result.getWinPercentage() > (100 - proData.getWinPercentage()))
|| (hasFactory
&& result.getWinPercentage() > (100 - proData.getMinWinPercentage()))
|| result.getTuvSwing() >= 0)) {
maxWinTerritory = t;
maxWinPercentage = result.getWinPercentage();
}
}
if (maxWinTerritory != null) {
ProTerritory to = moveMap.get(maxWinTerritory);
to.setBattleResult(null);
final List<Unit> unitsToAdd = ProTransportUtils.getUnitsToAdd(proData, unit, moveMap);
to.addTempUnits(unitsToAdd);
addedUnits.addAll(unitsToAdd);
moveAlliedCarriedFighters(unit, to);
}
}
sortedUnitMoveOptions.keySet().removeAll(addedUnits);
// Set air units in territories
for (final Unit unit : sortedUnitMoveOptions.keySet()) {
Territory maxWinTerritory = null;
double maxWinPercentage = -1;
for (final Territory t : sortedUnitMoveOptions.get(unit)) {
final ProTerritory proTerritory = moveMap.get(t);
if (t.isWater()
&& Matches.unitIsAir().test(unit)
&& !ProTransportUtils.validateCarrierCapacity(
player, t, proTerritory.getAllDefendersForCarrierCalcs(data, player), unit)) {
continue; // skip moving air to water if not enough carrier capacity
}
if (!t.isWater()
&& !t.isOwnedBy(player)
&& Matches.unitIsAir().test(unit)
&& !ProMatches.territoryHasInfraFactoryAndIsLand().test(t)) {
continue; // skip moving air units to allied land without a factory
}
proTerritory.setBattleResultIfNull(
() ->
calc.estimateDefendBattleResults(
proData, proTerritory, proTerritory.getEligibleDefenders(player)));
final ProBattleResult result = proTerritory.getBattleResult();
final boolean hasFactory = ProMatches.territoryHasInfraFactoryAndIsLand().test(t);
if (result.getWinPercentage() > maxWinPercentage
&& ((t.equals(proData.getMyCapital())
&& result.getWinPercentage() > (100 - proData.getWinPercentage()))
|| (hasFactory
&& result.getWinPercentage() > (100 - proData.getMinWinPercentage()))
|| result.getTuvSwing() >= 0)) {
maxWinTerritory = t;
maxWinPercentage = result.getWinPercentage();
}
}
if (maxWinTerritory != null) {
moveMap.get(maxWinTerritory).addTempUnit(unit);
moveMap.get(maxWinTerritory).setBattleResult(null);
addedUnits.add(unit);
}
}
sortedUnitMoveOptions.keySet().removeAll(addedUnits);
// Loop through all my transports and see which territories they can defend from current list
final List<Unit> alreadyMovedTransports = new ArrayList<>();
if (!Properties.getTransportCasualtiesRestricted(data.getProperties())) {
final Map<Unit, Set<Territory>> transportDefendOptions = new HashMap<>();
for (final Unit unit : transportMoveMap.keySet()) {
// Find number of defend options
final Set<Territory> canDefendTerritories = new HashSet<>();
for (final ProTerritory attackTerritoryData : territoriesToTryToDefend) {
if (transportMoveMap.get(unit).contains(attackTerritoryData.getTerritory())) {
canDefendTerritories.add(attackTerritoryData.getTerritory());
}
}
if (!canDefendTerritories.isEmpty()) {
transportDefendOptions.put(unit, canDefendTerritories);
}
}
// Loop through transports with move options and determine if any naval defense needs it
for (final Unit transport : transportDefendOptions.keySet()) {
// Find current naval defense that needs transport if it isn't transporting units
for (final Territory t : transportDefendOptions.get(transport)) {
if (!transport.isTransporting(proData.getUnitTerritory(transport))) {
final ProTerritory proTerritory = moveMap.get(t);
proTerritory.setBattleResultIfNull(
() ->
calc.estimateDefendBattleResults(
proData, proTerritory, proTerritory.getAllDefenders()));
final ProBattleResult result = proTerritory.getBattleResult();
if (result.getTuvSwing() > 0) {
proTerritory.addTempUnit(transport);
proTerritory.setBattleResult(null);
alreadyMovedTransports.add(transport);
ProLogger.trace("Adding defend transport to: " + t.getName());
break;
}
}
}
}
}
// Loop through all my transports and see which can make amphib move
final Map<Unit, Set<Territory>> amphibMoveOptions = new HashMap<>();
for (final ProTransport proTransportData : transportMapList) {
// If already used to defend then ignore
if (alreadyMovedTransports.contains(proTransportData.getTransport())) {
continue;
}
// Find number of amphib move options
final Set<Territory> canAmphibMoveTerritories = new HashSet<>();
for (final ProTerritory attackTerritoryData : territoriesToTryToDefend) {
if (proTransportData.getTransportMap().containsKey(attackTerritoryData.getTerritory())) {
canAmphibMoveTerritories.add(attackTerritoryData.getTerritory());
}
}
if (!canAmphibMoveTerritories.isEmpty()) {
amphibMoveOptions.put(proTransportData.getTransport(), canAmphibMoveTerritories);
}
}
// Loop through transports with amphib move options and determine if any land defense needs it
for (final Unit transport : amphibMoveOptions.keySet()) {
// Find current land defense results for territories that unit can amphib move
for (final Territory t : amphibMoveOptions.get(transport)) {
final ProTerritory proTerritory = moveMap.get(t);
proTerritory.setBattleResultIfNull(
() ->
calc.estimateDefendBattleResults(
proData, proTerritory, proTerritory.getAllDefenders()));
final ProBattleResult result = proTerritory.getBattleResult();
final boolean hasFactory = ProMatches.territoryHasInfraFactoryAndIsLand().test(t);
if ((t.equals(proData.getMyCapital())
&& result.getWinPercentage() > (100 - proData.getWinPercentage()))
|| (hasFactory && result.getWinPercentage() > (100 - proData.getMinWinPercentage()))
|| result.getTuvSwing() > 0) {
// Get all units that have already moved
final List<Unit> alreadyMovedUnits = new ArrayList<>();
for (final ProTerritory t2 : moveMap.values()) {
alreadyMovedUnits.addAll(t2.getUnits());
alreadyMovedUnits.addAll(t2.getTempUnits());
}
// Find units that haven't moved and can be transported
boolean addedAmphibUnits = false;
for (final ProTransport proTransportData : transportMapList) {
if (proTransportData.getTransport().equals(transport)) {
// Find units to transport
final Set<Territory> territoriesCanLoadFrom =
proTransportData.getTransportMap().get(t);
final List<Unit> amphibUnitsToAdd =
ProTransportUtils.getUnitsToTransportFromTerritories(
player, transport, territoriesCanLoadFrom, alreadyMovedUnits);
if (amphibUnitsToAdd.isEmpty()) {
continue;
}
// Find safest territory to unload from
double minStrengthDifference = Double.POSITIVE_INFINITY;
Territory minTerritory = null;
final Set<Territory> territoriesToMoveTransport =
data.getMap()
.getNeighbors(t, ProMatches.territoryCanMoveSeaUnits(player, isCombatMove));
final Set<Territory> loadFromTerritories = new HashSet<>();
for (final Unit u : amphibUnitsToAdd) {
loadFromTerritories.add(unitTerritoryMap.get(u));
}
for (final Territory territoryToMoveTransport : territoriesToMoveTransport) {
final ProTerritory proDestination = moveMap.get(territoryToMoveTransport);
if (proTransportData.getSeaTransportMap().containsKey(territoryToMoveTransport)
&& proTransportData
.getSeaTransportMap()
.get(territoryToMoveTransport)
.containsAll(loadFromTerritories)
&& proDestination != null
&& (proDestination.isCanHold() || hasFactory)) {
final List<Unit> attackers = proDestination.getMaxEnemyUnits();
final Collection<Unit> defenders = proDestination.getAllDefenders();
defenders.add(transport);
final double strengthDifference =
ProBattleUtils.estimateStrengthDifference(
territoryToMoveTransport, attackers, defenders);
if (strengthDifference < minStrengthDifference) {
minTerritory = territoryToMoveTransport;
minStrengthDifference = strengthDifference;
}
}
}
if (minTerritory != null) {
// Add amphib defense
proTerritory.getTransportTerritoryMap().put(transport, minTerritory);
proTerritory.addTempUnits(amphibUnitsToAdd);
proTerritory.putTempAmphibAttackMap(transport, amphibUnitsToAdd);
proTerritory.setBattleResult(null);