-
Notifications
You must be signed in to change notification settings - Fork 379
/
CasualtySelector.java
304 lines (287 loc) · 11.1 KB
/
CasualtySelector.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
package games.strategy.triplea.delegate.battle.casualty;
import games.strategy.engine.data.GameData;
import games.strategy.engine.data.GamePlayer;
import games.strategy.engine.data.Territory;
import games.strategy.engine.data.Unit;
import games.strategy.engine.data.UnitType;
import games.strategy.engine.delegate.IDelegateBridge;
import games.strategy.engine.player.Player;
import games.strategy.triplea.Properties;
import games.strategy.triplea.ai.weak.WeakAi;
import games.strategy.triplea.attachments.UnitAttachment;
import games.strategy.triplea.delegate.DiceRoll;
import games.strategy.triplea.delegate.Matches;
import games.strategy.triplea.delegate.data.CasualtyDetails;
import games.strategy.triplea.delegate.data.CasualtyList;
import games.strategy.triplea.delegate.power.calculator.CombatValue;
import games.strategy.triplea.formatter.MyFormatter;
import games.strategy.triplea.util.UnitCategory;
import games.strategy.triplea.util.UnitSeparator;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.triplea.java.collections.CollectionUtils;
import org.triplea.java.collections.IntegerMap;
import org.triplea.util.Tuple;
/**
* Utility class for determining casualties and selecting casualties. The code was being duplicated
* all over the place.
*/
@Slf4j
@UtilityClass
public class CasualtySelector {
public static void clearOolCache() {
CasualtyOrderOfLosses.clearOolCache();
}
/**
* Selects casualties for the specified battle.
*
* @param battleId may be null if we are not in a battle (eg, if this is an aa fire due to
* moving).
*/
public static CasualtyDetails selectCasualties(
final GamePlayer player,
final Collection<Unit> targetsToPickFrom,
final CombatValue combatValue,
final Territory battleSite,
final IDelegateBridge bridge,
final String text,
final DiceRoll dice,
final UUID battleId,
final boolean headLess,
final int extraHits,
final boolean allowMultipleHitsPerUnit) {
if (targetsToPickFrom.isEmpty()) {
return new CasualtyDetails();
}
final GameData data = bridge.getData();
final Player tripleaPlayer =
player.isNull() ? new WeakAi(player.getName()) : bridge.getRemotePlayer(player);
final Map<Unit, Collection<Unit>> dependents =
headLess ? Map.of() : CasualtyUtil.getDependents(targetsToPickFrom);
final int hitsRemaining =
Properties.getTransportCasualtiesRestricted(data.getProperties())
? extraHits
: dice.getHits();
if (dice.getHits() == 0) {
return new CasualtyDetails();
}
// Create production cost map, Maybe should do this elsewhere, but in case prices change, we do
// it here.
final IntegerMap<UnitType> costs = bridge.getCostsForTuv(player);
final Tuple<CasualtyList, List<Unit>> defaultCasualtiesAndSortedTargets =
getDefaultCasualties(
targetsToPickFrom,
hitsRemaining,
player,
combatValue,
battleSite,
costs,
data,
allowMultipleHitsPerUnit);
final CasualtyList defaultCasualties = defaultCasualtiesAndSortedTargets.getFirst();
final List<Unit> sortedTargetsToPickFrom = defaultCasualtiesAndSortedTargets.getSecond();
if (sortedTargetsToPickFrom.size() != targetsToPickFrom.size()) {
throw new IllegalStateException(
"sortedTargetsToPickFrom must have the same size as targetsToPickFrom list");
}
final int totalHitpoints =
(allowMultipleHitsPerUnit
? CasualtyUtil.getTotalHitpointsLeft(sortedTargetsToPickFrom)
: sortedTargetsToPickFrom.size());
final CasualtyDetails casualtyDetails =
hitsRemaining >= totalHitpoints
|| sortedTargetsToPickFrom.size() == 1
|| allTargetsOneTypeOneHitPoint(
sortedTargetsToPickFrom,
dependents,
Properties.getPartialAmphibiousRetreat(data.getProperties()))
? new CasualtyDetails(defaultCasualties, true)
: tripleaPlayer.selectCasualties(
sortedTargetsToPickFrom,
dependents,
hitsRemaining,
text,
dice,
player,
combatValue.getFriendUnits(),
combatValue.getEnemyUnits(),
false,
List.of(),
defaultCasualties,
battleId,
battleSite,
allowMultipleHitsPerUnit);
if (!Properties.getPartialAmphibiousRetreat(data.getProperties())) {
final boolean unitsWithMarineBonusAndWasAmphibiousKilled =
casualtyDetails.getKilled().stream()
.anyMatch(u -> u.getUnitAttachment().getIsMarine() != 0 && u.getWasAmphibious());
if (unitsWithMarineBonusAndWasAmphibiousKilled) {
casualtyDetails.ensureUnitsWithPositiveMarineBonusAreKilledLast(sortedTargetsToPickFrom);
}
}
casualtyDetails.ensureUnitsAreKilledFirst(
sortedTargetsToPickFrom, Matches.unitIsAir(), Comparator.comparing(Unit::getMovementLeft));
casualtyDetails.ensureUnitsAreDamagedFirst(
sortedTargetsToPickFrom,
Matches.unitIsAir(),
Comparator.comparing(Unit::getMovementLeft).reversed());
final List<Unit> damaged = casualtyDetails.getDamaged();
final List<Unit> killed = casualtyDetails.getKilled();
int numhits = killed.size();
if (!allowMultipleHitsPerUnit) {
damaged.clear();
} else {
for (final Unit unit : killed) {
final UnitAttachment ua = unit.getUnitAttachment();
final int damageToUnit = Collections.frequency(damaged, unit);
// allowed damage
numhits += Math.max(0, Math.min(damageToUnit, (ua.getHitPoints() - (1 + unit.getHits()))));
// remove from damaged list, since they will die
damaged.removeIf(unit::equals);
}
}
// check right number
if (numhits + damaged.size() != Math.min(hitsRemaining, totalHitpoints)) {
tripleaPlayer.reportError("Wrong number of casualties selected");
if (headLess) {
log.error(
"Possible Infinite Loop: Wrong number of casualties selected: number of hits on units "
+ (numhits + damaged.size())
+ " != number of hits to take "
+ Math.min(hitsRemaining, totalHitpoints)
+ ", for "
+ casualtyDetails);
}
return selectCasualties(
player,
sortedTargetsToPickFrom,
combatValue,
battleSite,
bridge,
text,
dice,
battleId,
headLess,
extraHits,
allowMultipleHitsPerUnit);
}
// check we have enough of each type
if (!sortedTargetsToPickFrom.containsAll(killed)
|| !sortedTargetsToPickFrom.containsAll(damaged)) {
tripleaPlayer.reportError("Cannot remove enough units of those types");
if (headLess) {
log.error(
"Possible Infinite Loop: Cannot remove enough units of those types: targets "
+ MyFormatter.unitsToTextNoOwner(sortedTargetsToPickFrom)
+ ", for "
+ casualtyDetails);
}
return selectCasualties(
player,
sortedTargetsToPickFrom,
combatValue,
battleSite,
bridge,
text,
dice,
battleId,
headLess,
extraHits,
allowMultipleHitsPerUnit);
}
return casualtyDetails;
}
/**
* A unit with two hitpoints will be listed twice if they will die. The first time they are listed
* it is as damaged. The second time they are listed, it is dead.
*/
private static Tuple<CasualtyList, List<Unit>> getDefaultCasualties(
final Collection<Unit> targetsToPickFrom,
final int hits,
final GamePlayer player,
final CombatValue combatValue,
final Territory battlesite,
final IntegerMap<UnitType> costs,
final GameData data,
final boolean allowMultipleHitsPerUnit) {
final CasualtyList defaultCasualtySelection = new CasualtyList();
// Sort units by power and cost in ascending order
final List<Unit> sorted =
getCasualtyOrderOfLoss(targetsToPickFrom, player, combatValue, battlesite, costs, data);
// Remove two hit bb's selecting them first for default casualties
int numSelectedCasualties = 0;
if (allowMultipleHitsPerUnit) {
for (final Unit unit : sorted) {
// Stop if we have already selected as many hits as there are targets
if (numSelectedCasualties >= hits) {
return Tuple.of(defaultCasualtySelection, sorted);
}
final UnitAttachment ua = unit.getUnitAttachment();
final int extraHitPoints =
Math.min((hits - numSelectedCasualties), (ua.getHitPoints() - (1 + unit.getHits())));
for (int i = 0; i < extraHitPoints; i++) {
numSelectedCasualties++;
defaultCasualtySelection.addToDamaged(unit);
}
}
}
// Select units
for (final Unit unit : sorted) {
// Stop if we have already selected as many hits as there are targets
if (numSelectedCasualties >= hits) {
return Tuple.of(defaultCasualtySelection, sorted);
}
defaultCasualtySelection.addToKilled(unit);
numSelectedCasualties++;
}
return Tuple.of(defaultCasualtySelection, sorted);
}
public static List<Unit> getCasualtyOrderOfLoss(
final Collection<Unit> targetsToPickFrom,
final GamePlayer player,
final CombatValue combatValue,
final Territory battlesite,
final IntegerMap<UnitType> costs,
final GameData data) {
return CasualtyOrderOfLosses.sortUnitsForCasualtiesWithSupport(
CasualtyOrderOfLosses.Parameters.builder()
.targetsToPickFrom(targetsToPickFrom)
.player(player)
.combatValue(combatValue)
.battlesite(battlesite)
.costs(costs)
.data(data)
.build());
}
/**
* Checks if the given targets are all of one category as defined by <code>
* UnitSeparator.categorize</code> and if they are not multiple hit units.
*
* @param targets a collection of target units
* @param dependents map of dependent units for target units
*/
private static boolean allTargetsOneTypeOneHitPoint(
final Collection<Unit> targets,
final Map<Unit, Collection<Unit>> dependents,
final boolean separateByRetreatPossibility) {
final Set<UnitCategory> categorized =
UnitSeparator.categorize(
targets,
UnitSeparator.SeparatorCategories.builder()
.retreatPossibility(separateByRetreatPossibility)
.dependents(dependents)
.build());
if (categorized.size() == 1) {
final UnitCategory unitCategory = CollectionUtils.getAny(categorized);
return unitCategory.getHitPoints() - unitCategory.getDamaged() <= 1;
}
return false;
}
}