-
Notifications
You must be signed in to change notification settings - Fork 379
/
MovePanel.java
1586 lines (1519 loc) · 67 KB
/
MovePanel.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.ui;
import games.strategy.common.delegate.BaseEditDelegate;
import games.strategy.debug.ClientLogger;
import games.strategy.engine.data.GameData;
import games.strategy.engine.data.PlayerID;
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.triplea.Constants;
import games.strategy.triplea.TripleAUnit;
import games.strategy.triplea.attachments.TechAttachment;
import games.strategy.triplea.attachments.UnitAttachment;
import games.strategy.triplea.delegate.AbstractMoveDelegate;
import games.strategy.triplea.delegate.AbstractMoveDelegate.MoveType;
import games.strategy.triplea.delegate.GameStepPropertiesHelper;
import games.strategy.triplea.delegate.Matches;
import games.strategy.triplea.delegate.MoveValidator;
import games.strategy.triplea.delegate.TransportTracker;
import games.strategy.triplea.delegate.UnitComparator;
import games.strategy.triplea.delegate.dataObjects.MoveDescription;
import games.strategy.triplea.delegate.dataObjects.MoveValidationResult;
import games.strategy.triplea.delegate.dataObjects.MustMoveWithDetails;
import games.strategy.triplea.util.TransportUtils;
import games.strategy.triplea.util.UnitCategory;
import games.strategy.triplea.util.UnitSeperator;
import games.strategy.util.CompositeMatch;
import games.strategy.util.CompositeMatchAnd;
import games.strategy.util.CompositeMatchOr;
import games.strategy.util.IntegerMap;
import games.strategy.util.InverseMatch;
import games.strategy.util.Match;
import games.strategy.util.Util;
import java.awt.Image;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.lang.ref.WeakReference;
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.Set;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JOptionPane;
public class MovePanel extends AbstractMovePanel {
private static final long serialVersionUID = 5004515340964828564L;
private static final int s_defaultMinTransportCost = 5;
/**
* @param s_deselectNumber
* adds or removes 10 units (used to remove 1/s_deselectNumber of total units (useful for splitting large
* armies), but changed it
* after feedback)
*/
private static final int s_deselectNumber = 10;
// access only through getter and setter!
private Territory m_firstSelectedTerritory;
private Territory m_selectedEndpointTerritory;
private Territory m_mouseCurrentTerritory;
private Territory m_lastFocusedTerritory;
private List<Territory> m_forced;
private boolean m_nonCombat;
private Point m_mouseSelectedPoint;
private Point m_mouseCurrentPoint;
private Point m_mouseLastUpdatePoint;
// use a LinkedHashSet because we want to know the order
private final Set<Unit> m_selectedUnits = new LinkedHashSet<Unit>();
private static Map<Unit, Collection<Unit>> s_dependentUnits = new HashMap<Unit, Collection<Unit>>();
// the must move with details for the currently selected territory
// note this is kept in sync because we do not modify m_selectedTerritory directly
// instead we only do so through the private setter
private MustMoveWithDetails m_mustMoveWithDetails = null;
// cache this so we can update it only when territory/units change
private List<Unit> m_unitsThatCanMoveOnRoute;
private Image m_currentCursorImage;
private Route m_routeCached = null;
private String m_displayText = "Combat Move";
private MoveType m_moveType = MoveType.DEFAULT;
/** Creates new MovePanel */
public MovePanel(final GameData data, final MapPanel map, final TripleAFrame frame) {
super(data, map, frame);
m_undoableMovesPanel = new UndoableMovesPanel(data, this);
m_mouseCurrentTerritory = null;
m_unitsThatCanMoveOnRoute = Collections.emptyList();
m_currentCursorImage = null;
}
// Same as above! Delete this crap after refactoring.
public static void clearDependents(final Collection<Unit> units) {
for (final Unit unit : units) {
if (Matches.UnitIsAirTransport.match(unit)) {
s_dependentUnits.remove(unit);
}
}
}
@Override
protected void clearDependencies() {
s_dependentUnits.clear();
}
public void setMoveType(final MoveType moveType) {
m_moveType = moveType;
}
private PlayerID getUnitOwner(final Collection<Unit> units) {
if (BaseEditDelegate.getEditMode(getData()) && units != null && !units.isEmpty()) {
return units.iterator().next().getOwner();
} else {
return getCurrentPlayer();
}
}
/**
* Sort the specified units in preferred movement or unload order.
*/
private void sortUnitsToMove(final List<Unit> units, final Route route) {
if (units == null || units.isEmpty()) {
return;
} else if (route == null) {
final Exception nullRouteError = (new IllegalArgumentException("route is not supposed to be null"));
ClientLogger.logQuietly(
"Programming error, route should not be null here. Aborting sort operation and returning.", nullRouteError);
}
final Comparator<Unit> unitComparator;
// sort units based on which transports are allowed to unload
if (route.isUnload() && Match.someMatch(units, Matches.UnitIsLand)) {
unitComparator = UnitComparator.getUnloadableUnitsComparator(units, route, getUnitOwner(units), true);
} else {
unitComparator = UnitComparator.getMovableUnitsComparator(units, route);
}
Collections.sort(units, unitComparator);
}
/**
* Sort the specified transports in preferred load order.
*/
private void sortTransportsToLoad(final List<Unit> transports, final Route route) {
if (transports.isEmpty()) {
return;
}
Collections.sort(transports,
UnitComparator.getLoadableTransportsComparator(transports, route, getUnitOwner(transports)));
}
/**
* Sort the specified transports in preferred unload order.
*/
private void sortTransportsToUnload(final List<Unit> transports, final Route route) {
if (transports.isEmpty()) {
return;
}
Collections.sort(transports,
UnitComparator.getUnloadableTransportsComparator(transports, route, getUnitOwner(transports), true));
}
/**
* Return the units that are to be unloaded for this route.
* If needed will ask the user what transports to unload.
* This is needed because the user needs to be able to select what transports to unload
* in the case where some transports have different movement, different
* units etc
*/
private Collection<Unit> getUnitsToUnload(final Route route, final Collection<Unit> unitsToUnload) {
final Collection<Unit> allUnits = getFirstSelectedTerritory().getUnits().getUnits();
final List<Unit> candidateUnits = Match.getMatches(allUnits, getUnloadableMatch(route, unitsToUnload));
if (unitsToUnload.size() == candidateUnits.size()) {
return unitsToUnload;
}
final List<Unit> candidateTransports =
Match.getMatches(allUnits, Matches.unitIsTransportingSomeCategories(candidateUnits));
// remove all incapable transports
final Collection<Unit> incapableTransports =
Match.getMatches(candidateTransports, Matches.transportCannotUnload(route.getEnd()));
candidateTransports.removeAll(incapableTransports);
if (candidateTransports.size() == 0) {
return Collections.emptyList();
}
// just one transport, dont bother to ask
if (candidateTransports.size() == 1) {
return unitsToUnload;
}
// are the transports all of the same type
// if they are, then don't ask
final Collection<UnitCategory> categories =
UnitSeperator.categorize(candidateTransports, m_mustMoveWithDetails.getMustMoveWith(), true, false);
if (categories.size() == 1) {
return unitsToUnload;
}
sortTransportsToUnload(candidateTransports, route);
// unitsToUnload are actually dependents, but need to select transports
final Map<Unit, Unit> unitsToTransports = TransportUtils.mapTransports(route, unitsToUnload, candidateTransports);
final Set<Unit> defaultSelections = new HashSet<Unit>(unitsToTransports.values());
// match criteria to ensure that chosen transports will match selected units
final Match<Collection<Unit>> transportsToUnloadMatch = new Match<Collection<Unit>>() {
@Override
public boolean match(final Collection<Unit> units) {
final List<Unit> sortedTransports = Match.getMatches(units, Matches.UnitIsTransport);
final Collection<Unit> availableUnits = new ArrayList<Unit>(unitsToUnload);
// track the changing capacities of the transports as we assign units
final IntegerMap<Unit> capacityMap = new IntegerMap<Unit>();
for (final Unit transport : sortedTransports) {
final Collection<Unit> transporting = TripleAUnit.get(transport).getTransporting();
capacityMap.add(transport, TransportUtils.getTransportCost(transporting));
}
boolean hasChanged = false;
final Comparator<Unit> increasingCapacityComparator =
UnitComparator.getIncreasingCapacityComparator(sortedTransports);
// This algorithm will ensure that it is actually possible to distribute
// the selected units amongst the current selection of chosen transports.
do {
hasChanged = false;
// sort transports by increasing capacity
Collections.sort(sortedTransports, increasingCapacityComparator);
// try to remove one unit from each transport, in succession
final Iterator<Unit> transportIter = sortedTransports.iterator();
while (transportIter.hasNext()) {
final Unit transport = transportIter.next();
final Collection<Unit> transporting = TripleAUnit.get(transport).getTransporting();
if (transporting == null) {
continue;
}
final Collection<UnitCategory> transCategories = UnitSeperator.categorize(transporting);
final Iterator<Unit> unitIter = availableUnits.iterator();
while (unitIter.hasNext()) {
final Unit unit = unitIter.next();
final Collection<UnitCategory> unitCategory = UnitSeperator.categorize(Collections.singleton(unit));
// is one of the transported units of the same type we want to unload?
if (Util.someIntersect(transCategories, unitCategory)) {
// unload the unit, remove the transport from our list, and continue
hasChanged = true;
unitIter.remove();
transportIter.remove();
break;
}
}
}
// repeat until there are no units left or no changes occur
} while (availableUnits.size() > 0 && hasChanged);
// if we haven't seen all of the transports (and removed them)
// then there are extra transports that don't fit.
return (sortedTransports.size() == 0);
}
};
// choosing what transports to unload
final UnitChooser chooser = new UnitChooser(candidateTransports, defaultSelections,
m_mustMoveWithDetails.getMustMoveWith(), /* categorizeMovement */true, /* categorizeTransportCost */false,
getGameData(), /* allowTwoHit */false, getMap().getUIContext(), transportsToUnloadMatch);
chooser.setTitle("What transports do you want to unload");
final int option =
JOptionPane.showOptionDialog(getTopLevelAncestor(), chooser, "What transports do you want to unload",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, null, null);
if (option != JOptionPane.OK_OPTION) {
return Collections.emptyList();
}
final String title = "unload";
final String action = "unload";
final Collection<Unit> chosenUnits =
UserChooseUnits(defaultSelections, transportsToUnloadMatch, candidateTransports, title, action);
final Collection<Unit> choosenTransports = Match.getMatches(chosenUnits, Matches.UnitIsTransport);
// Collection<Unit> choosenTransports = Match.getMatches(chooser.getSelected(), Matches.UnitIsTransport);
final List<Unit> allUnitsInSelectedTransports = new ArrayList<Unit>();
for (final Unit transport : choosenTransports) {
final Collection<Unit> transporting = TripleAUnit.get(transport).getTransporting();
if (transporting != null) {
allUnitsInSelectedTransports.addAll(transporting);
}
}
allUnitsInSelectedTransports.retainAll(candidateUnits);
sortUnitsToMove(allUnitsInSelectedTransports, route);
final List<Unit> rVal = new ArrayList<Unit>();
final List<Unit> sortedTransports = new ArrayList<Unit>(choosenTransports);
Collections.sort(sortedTransports, UnitComparator.getIncreasingCapacityComparator(sortedTransports));
final Collection<Unit> selectedUnits = new ArrayList<Unit>(unitsToUnload);
// first pass: choose one unit from each selected transport
for (final Unit transport : sortedTransports) {
boolean hasChanged = false;
final Iterator<Unit> selectedIter = selectedUnits.iterator();
while (selectedIter.hasNext()) {
final Unit selected = selectedIter.next();
final Collection<Unit> transporting = TripleAUnit.get(transport).getTransporting();
for (final Unit candidate : transporting) {
if (selected.getType().equals(candidate.getType()) && selected.getOwner().equals(candidate.getOwner())
&& selected.getHits() == candidate.getHits()) {
hasChanged = true;
rVal.add(candidate);
allUnitsInSelectedTransports.remove(candidate);
selectedIter.remove();
break;
}
}
if (hasChanged) {
break;
}
}
}
// now fill remaining slots in preferred unit order
for (final Unit selected : selectedUnits) {
final Iterator<Unit> candidateIter = allUnitsInSelectedTransports.iterator();
while (candidateIter.hasNext()) {
final Unit candidate = candidateIter.next();
if (selected.getType().equals(candidate.getType()) && selected.getOwner().equals(candidate.getOwner())
&& selected.getHits() == candidate.getHits()) {
rVal.add(candidate);
candidateIter.remove();
break;
}
}
}
return rVal;
}
private CompositeMatch<Unit> getUnloadableMatch(final Route route, final Collection<Unit> units) {
final CompositeMatch<Unit> unloadable = new CompositeMatchAnd<Unit>();
unloadable.add(getMovableMatch(route, units));
unloadable.add(Matches.UnitIsLand);
return unloadable;
}
private CompositeMatch<Unit> getMovableMatch(final Route route, final Collection<Unit> units) {
final CompositeMatch<Unit> movable = new CompositeMatchAnd<Unit>();
if (!BaseEditDelegate.getEditMode(getData())) {
movable.add(Matches.unitIsOwnedBy(getCurrentPlayer()));
}
/*
* if you do not have selection of zero-movement units enabled,
* this will restrict selection to units with 1 or more movement
*/
if (!games.strategy.triplea.Properties.getSelectableZeroMovementUnits(getData())) {
movable.add(Matches.UnitCanMove);
}
if (!m_nonCombat) {
movable.add(Matches.UnitCanNotMoveDuringCombatMove.invert());
}
if (route != null) {
final Match<Unit> enoughMovement = new Match<Unit>() {
@Override
public boolean match(final Unit u) {
if (BaseEditDelegate.getEditMode(getData())) {
return true;
}
return TripleAUnit.get(u).getMovementLeft() >= route.getMovementCost(u);
}
};
if (route.isUnload()) {
final CompositeMatch<Unit> landOrCanMove = new CompositeMatchOr<Unit>();
landOrCanMove.add(Matches.UnitIsLand);
final CompositeMatch<Unit> notLandAndCanMove = new CompositeMatchAnd<Unit>();
notLandAndCanMove.add(enoughMovement);
notLandAndCanMove.add(Matches.UnitIsNotLand);
landOrCanMove.add(notLandAndCanMove);
movable.add(landOrCanMove);
} else {
movable.add(enoughMovement);
}
}
if (route != null && route.getEnd() != null) {
final boolean water = route.getEnd().isWater();
if (water && !route.isLoad()) {
movable.add(Matches.UnitIsNotLand);
}
if (!water) {
movable.add(Matches.UnitIsNotSea);
}
}
if (units != null && !units.isEmpty()) {
// force all units to have the same owner in edit mode
final PlayerID owner = getUnitOwner(units);
if (BaseEditDelegate.getEditMode(getData())) {
movable.add(Matches.unitIsOwnedBy(owner));
}
final CompositeMatch<Unit> rightUnitTypeMatch = new CompositeMatchOr<Unit>();
for (final Unit unit : units) {
if (unit.getOwner().equals(owner)) {
rightUnitTypeMatch.add(Matches.unitIsOfType(unit.getType()));
}
}
movable.add(rightUnitTypeMatch);
}
return movable;
}
private Route getRoute(final Territory start, final Territory end, final Collection<Unit> selectedUnits) {
getData().acquireReadLock();
try {
if (m_forced == null) {
return getRouteNonForced(start, end, selectedUnits);
} else {
return getRouteForced(start, end, selectedUnits);
}
} finally {
getData().releaseReadLock();
}
}
/**
* Get the route including the territories that we are forced to move through.
*/
private Route getRouteForced(final Territory start, final Territory end, final Collection<Unit> selectedUnits) {
if (m_forced == null || m_forced.size() == 0) {
throw new IllegalStateException("No forced territories:" + m_forced + " end:" + end + " start:" + start);
}
final Iterator<Territory> iter = m_forced.iterator();
Territory last = getFirstSelectedTerritory();
Territory current = null;
Route total = new Route();
total.setStart(last);
while (iter.hasNext()) {
current = iter.next();
final Route add = getData().getMap().getRoute(last, current);
final Route newTotal = Route.join(total, add);
if (newTotal == null) {
return total;
}
total = newTotal;
last = current;
}
if (!end.equals(last)) {
final Route add = getRouteNonForced(last, end, selectedUnits);
final Route newTotal = Route.join(total, add);
if (newTotal != null) {
total = newTotal;
}
}
return total;
}
/**
* Get the route ignoring forced territories
*/
private Route getRouteNonForced(final Territory start, final Territory end, final Collection<Unit> selectedUnits) {
// can't rely on current player being the unit owner in Edit Mode
// look at the units being moved to determine allies and enemies
final PlayerID owner = getUnitOwner(selectedUnits);
return MoveValidator.getBestRoute(start, end, getData(), owner, selectedUnits,
!GameStepPropertiesHelper.isAirborneMove(getData()));
}
private void updateUnitsThatCanMoveOnRoute(final Collection<Unit> units, final Route route) {
if (route == null || route.hasNoSteps()) {
clearStatusMessage();
getMap().showMouseCursor();
m_currentCursorImage = null;
m_unitsThatCanMoveOnRoute = new ArrayList<Unit>(units);
return;
}
getMap().hideMouseCursor();
// TODO kev check for already loaded airTransports
Collection<Unit> transportsToLoad = Collections.emptyList();
if (MoveValidator.isLoad(units, s_dependentUnits, route, getData(), getCurrentPlayer())) {
transportsToLoad = route.getEnd().getUnits().getMatches(
new CompositeMatchAnd<Unit>(Matches.UnitIsTransport, Matches.alliedUnit(getCurrentPlayer(), getData())));
}
List<Unit> best = new ArrayList<Unit>(units);
// if the player selects a land unit and other units
// when the
// only consider the non land units
if (route.getStart().isWater() && route.getEnd() != null && route.getEnd().isWater() && !route.isLoad()) {
best = Match.getMatches(best, new InverseMatch<Unit>(Matches.UnitIsLand));
}
sortUnitsToMove(best, route);
Collections.reverse(best);
List<Unit> bestWithDependents = addMustMoveWith(best);
MoveValidationResult allResults;
getData().acquireReadLock();
try {
allResults = AbstractMoveDelegate.validateMove(m_moveType, bestWithDependents, route, getCurrentPlayer(),
transportsToLoad, s_dependentUnits, m_nonCombat, getUndoableMoves(), getData());
} finally {
getData().releaseReadLock();
}
MoveValidationResult lastResults = allResults;
if (!allResults.isMoveValid()) {
// if the player is invading only consider units that can invade
if (!m_nonCombat && route.isUnload()
&& Matches.isTerritoryEnemy(getCurrentPlayer(), getData()).match(route.getEnd())) {
best = Match.getMatches(best, Matches.UnitCanInvade);
bestWithDependents = addMustMoveWith(best);
lastResults = AbstractMoveDelegate.validateMove(m_moveType, bestWithDependents, route, getCurrentPlayer(),
transportsToLoad, s_dependentUnits, m_nonCombat, getUndoableMoves(), getData());
}
while (!best.isEmpty() && !lastResults.isMoveValid()) {
best = best.subList(1, best.size());
bestWithDependents = addMustMoveWith(best);
lastResults = AbstractMoveDelegate.validateMove(m_moveType, bestWithDependents, route, getCurrentPlayer(),
transportsToLoad, s_dependentUnits, m_nonCombat, getUndoableMoves(), getData());
}
}
if (allResults.isMoveValid()) {
// valid move
if (bestWithDependents.containsAll(m_selectedUnits)) {
clearStatusMessage();
m_currentCursorImage = null;
} else {
setStatusWarningMessage("Not all units can move there");
m_currentCursorImage = getMap().getWarningImage();
}
} else {
String message = allResults.getError();
if (message == null) {
message = allResults.getDisallowedUnitWarning(0);
}
if (message == null) {
message = allResults.getUnresolvedUnitWarning(0);
}
if (!lastResults.isMoveValid()) {
setStatusErrorMessage(message);
m_currentCursorImage = getMap().getErrorImage();
} else {
setStatusWarningMessage(message);
m_currentCursorImage = getMap().getWarningImage();
}
}
if (m_unitsThatCanMoveOnRoute.size() != new HashSet<Unit>(m_unitsThatCanMoveOnRoute).size()) {
cancelMove();
return;
}
m_unitsThatCanMoveOnRoute = new ArrayList<Unit>(bestWithDependents);
}
private List<Unit> addMustMoveWith(final List<Unit> best) {
final List<Unit> bestWithDependents = new ArrayList<Unit>(best);
for (final Unit u : best) {
if (m_mustMoveWithDetails.getMustMoveWith().containsKey(u)) {
final Collection<Unit> mustMoveWith = m_mustMoveWithDetails.getMustMoveWith().get(u);
if (mustMoveWith != null) {
for (final Unit m : mustMoveWith) {
if (!bestWithDependents.contains(m)) {
bestWithDependents.addAll(mustMoveWith);
}
}
}
}
}
return bestWithDependents;
}
/**
* Route can be null.
*/
final void updateRouteAndMouseShadowUnits(final Route route) {
m_routeCached = route;
getMap().setRoute(route, m_mouseSelectedPoint, m_mouseCurrentPoint, m_currentCursorImage);
if (route == null) {
getMap().setMouseShadowUnits(null);
} else {
getMap().setMouseShadowUnits(m_unitsThatCanMoveOnRoute);
}
}
/**
* Allow the user to select what transports to load.
* If null is returned, the move should be canceled.
*/
private Collection<Unit> getTransportsToLoad(final Route route, final Collection<Unit> unitsToLoad,
final boolean disablePrompts) {
if (!route.isLoad()) {
return Collections.emptyList();
}
if (Match.someMatch(unitsToLoad, Matches.UnitIsAir)) {
return Collections.emptyList();
}
final Collection<Unit> endOwnedUnits = route.getEnd().getUnits().getUnits();
final PlayerID unitOwner = getUnitOwner(unitsToLoad);
final MustMoveWithDetails endMustMoveWith =
MoveValidator.getMustMoveWith(route.getEnd(), endOwnedUnits, s_dependentUnits, getData(), unitOwner);
int minTransportCost = s_defaultMinTransportCost;
for (final Unit unit : unitsToLoad) {
minTransportCost = Math.min(minTransportCost, UnitAttachment.get(unit.getType()).getTransportCost());
}
final CompositeMatch<Unit> candidateTransportsMatch = new CompositeMatchAnd<Unit>();
candidateTransportsMatch.add(Matches.UnitIsTransport);
candidateTransportsMatch.add(Matches.alliedUnit(unitOwner, getGameData()));
final List<Unit> candidateTransports = Match.getMatches(endOwnedUnits, candidateTransportsMatch);
// remove transports that don't have enough capacity
final Iterator<Unit> transportIter = candidateTransports.iterator();
while (transportIter.hasNext()) {
final Unit transport = transportIter.next();
final int capacity = TransportTracker.getAvailableCapacity(transport);
if (capacity < minTransportCost) {
transportIter.remove();
}
}
// nothing to choose
if (candidateTransports.isEmpty()) {
return Collections.emptyList();
}
// sort transports in preferred load order
sortTransportsToLoad(candidateTransports, route);
final List<Unit> availableUnits = new ArrayList<Unit>(unitsToLoad);
final IntegerMap<Unit> availableCapacityMap = new IntegerMap<Unit>();
for (final Unit transport : candidateTransports) {
final int capacity = TransportTracker.getAvailableCapacity(transport);
availableCapacityMap.put(transport, capacity);
}
final Set<Unit> defaultSelections = new HashSet<Unit>();
// Algorithm to choose defaultSelections (transports to load)
// This algorithm uses mapTransports(), except mapTransports operates on
// transports that have already been selected for loading.
// We are trying to determine which transports are the best defaults to select for loading,
// and so we need a modified algorithm based strictly on candidateTransports order:
// - owned, capable transports are chosen first; attempt to fill them
// - allied, capable transports are chosen next; attempt to fill them
// - finally, incapable transports are chosen last (will generate errors)
// Note that if any allied transports qualify as defaults, we will always prompt with a
// UnitChooser later on so that it is obvious to the player.
boolean useAlliedTransports = false;
final Collection<Unit> capableTransports = new ArrayList<Unit>(candidateTransports);
// only allow incapable transports for updateUnitsThatCanMoveOnRoute
// so that we can have a nice UI error shown if these transports
// are selected, since it may not be obvious
final Collection<Unit> incapableTransports =
Match.getMatches(capableTransports, Matches.transportCannotUnload(route.getEnd()));
capableTransports.removeAll(incapableTransports);
final Match<Unit> alliedMatch = new Match<Unit>() {
@Override
public boolean match(final Unit transport) {
return (!transport.getOwner().equals(unitOwner));
}
};
final Collection<Unit> alliedTransports = Match.getMatches(capableTransports, alliedMatch);
capableTransports.removeAll(alliedTransports);
// First, load capable transports
final Map<Unit, Unit> unitsToCapableTransports =
TransportUtils.mapTransportsToLoadUsingMinTransports(availableUnits, capableTransports);
for (final Unit unit : unitsToCapableTransports.keySet()) {
final Unit transport = unitsToCapableTransports.get(unit);
final int unitCost = UnitAttachment.get(unit.getType()).getTransportCost();
availableCapacityMap.add(transport, (-1 * unitCost));
defaultSelections.add(transport);
}
availableUnits.removeAll(unitsToCapableTransports.keySet());
// Next, load allied transports
final Map<Unit, Unit> unitsToAlliedTransports =
TransportUtils.mapTransportsToLoadUsingMinTransports(availableUnits, alliedTransports);
for (final Unit unit : unitsToAlliedTransports.keySet()) {
final Unit transport = unitsToAlliedTransports.get(unit);
final int unitCost = UnitAttachment.get(unit.getType()).getTransportCost();
availableCapacityMap.add(transport, (-1 * unitCost));
defaultSelections.add(transport);
useAlliedTransports = true;
}
availableUnits.removeAll(unitsToAlliedTransports.keySet());
// only allow incapable transports for updateUnitsThatCanMoveOnRoute
// so that we can have a nice UI error shown if these transports
// are selected, since it may not be obvious
if (getSelectedEndpointTerritory() == null) {
final Map<Unit, Unit> unitsToIncapableTransports =
TransportUtils.mapTransportsToLoadUsingMinTransports(availableUnits, incapableTransports);
for (final Unit unit : unitsToIncapableTransports.keySet()) {
final Unit transport = unitsToIncapableTransports.get(unit);
final int unitCost = UnitAttachment.get(unit.getType()).getTransportCost();
availableCapacityMap.add(transport, (-1 * unitCost));
defaultSelections.add(transport);
}
availableUnits.removeAll(unitsToIncapableTransports.keySet());
} else {
candidateTransports.removeAll(incapableTransports);
}
// return defaults if we aren't allowed to prompt
if (disablePrompts) {
return defaultSelections;
}
// force UnitChooser to pop up if we are choosing allied transports
if (!useAlliedTransports) {
if (candidateTransports.size() == 1) {
return candidateTransports;
}
// all the same type, dont ask unless we have more than 1 unit type
if (UnitSeperator.categorize(candidateTransports, endMustMoveWith.getMustMoveWith(), true, false).size() == 1
&& unitsToLoad.size() == 1) {
return candidateTransports;
}
// If we've filled all transports, then no user intervention is required.
// It is possible to make "wrong" decisions if there are mixed unit types and
// mixed transport categories, but there is no UI to manage that anyway.
// Players will need to load incrementally in such cases.
if (defaultSelections.containsAll(candidateTransports)) {
boolean spaceLeft = false;
for (final Unit transport : candidateTransports) {
final int capacity = availableCapacityMap.getInt(transport);
if (capacity >= minTransportCost) {
spaceLeft = true;
break;
}
}
if (!spaceLeft) {
return candidateTransports;
}
}
}
// the match criteria to ensure that chosen transports will match selected units
final Match<Collection<Unit>> transportsToLoadMatch = new Match<Collection<Unit>>() {
@Override
public boolean match(final Collection<Unit> units) {
final Collection<Unit> transports = Match.getMatches(units, Matches.UnitIsTransport);
// prevent too many transports from being selected
return (transports.size() <= Math.min(unitsToLoad.size(), candidateTransports.size()));
}
};
final UnitChooser chooser = new UnitChooser(candidateTransports, defaultSelections,
endMustMoveWith.getMustMoveWith(), /* categorizeMovement */true, /* categorizeTransportCost */false,
getGameData(), /* allowTwoHit */false, getMap().getUIContext(), transportsToLoadMatch);
chooser.setTitle("What transports do you want to load");
final int option =
JOptionPane.showOptionDialog(getTopLevelAncestor(), chooser, "What transports do you want to load",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, null, null);
if (option != JOptionPane.OK_OPTION) {
return Collections.emptyList();
}
return chooser.getSelected(false);
}
private final UnitSelectionListener m_UNIT_SELECTION_LISTENER = new UnitSelectionListener() {
@Override
public void unitsSelected(final List<Unit> units, final Territory t, final MouseDetails me) {
if (!getListening()) {
return;
}
// check if we can handle this event, are we active?
if (!getActive()) {
return;
}
if (t == null) {
return;
}
final boolean rightMouse = me.isRightButton();
final boolean noSelectedTerritory = (m_firstSelectedTerritory == null);
final boolean isFirstSelectedTerritory = (m_firstSelectedTerritory == t);
// select units
final GameData data = getData();
data.acquireReadLock();
try {
// de select units
if (rightMouse && !noSelectedTerritory) {
deselectUnits(units, t, me);
} else if (!rightMouse && (noSelectedTerritory || isFirstSelectedTerritory)) {
selectUnitsToMove(units, t, me);
} else if (!rightMouse && me.isControlDown() && !isFirstSelectedTerritory) {
selectWayPoint(t);
} else if (!rightMouse && !noSelectedTerritory && !isFirstSelectedTerritory) {
selectEndPoint(t);
}
} finally {
data.releaseReadLock();
}
getMap().requestFocusInWindow();
}
private void selectUnitsToMove(final List<Unit> units, final Territory t, final MouseDetails me) {
// are any of the units ours, note - if no units selected thats still ok
if (!BaseEditDelegate.getEditMode(getData()) || !m_selectedUnits.isEmpty()) {
for (final Unit unit : units) {
if (!unit.getOwner().equals(getUnitOwner(m_selectedUnits))) {
return;
}
}
}
// basic match criteria only
final CompositeMatch<Unit> unitsToMoveMatch = getMovableMatch(null, null);
final Match<Collection<Unit>> ownerMatch = new Match<Collection<Unit>>() {
@Override
public boolean match(final Collection<Unit> unitsToCheck) {
final PlayerID owner = unitsToCheck.iterator().next().getOwner();
for (final Unit unit : unitsToCheck) {
if (!owner.equals(unit.getOwner())) {
return false;
}
}
return true;
}
};
if (units.isEmpty() && m_selectedUnits.isEmpty()) {
if (!me.isShiftDown()) {
final List<Unit> unitsToMove = t.getUnits().getMatches(unitsToMoveMatch);
if (unitsToMove.isEmpty()) {
return;
}
final String text = "Select units to move from " + t.getName();
UnitChooser chooser;
if (BaseEditDelegate.getEditMode(getData()) && !Match
.getMatches(unitsToMove, Matches.unitIsOwnedBy(getUnitOwner(unitsToMove))).containsAll(unitsToMove)) {
// use matcher to prevent units of different owners being chosen
chooser = new UnitChooser(unitsToMove, m_selectedUnits, /* mustMoveWith */null,
/* categorizeMovement */false, /* categorizeTransportCost */false, getData(), /* allowTwoHit */false,
getMap().getUIContext(), ownerMatch);
} else {
chooser =
new UnitChooser(unitsToMove, m_selectedUnits, /* mustMoveWith */null, /* categorizeMovement */false,
/* categorizeTransportCost */false, getData(), /* allowTwoHit */false, getMap().getUIContext());
}
final int option = JOptionPane.showOptionDialog(getTopLevelAncestor(), chooser, text,
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, null, null);
if (option != JOptionPane.OK_OPTION) {
return;
}
if (chooser.getSelected(false).isEmpty()) {
return;
}
m_selectedUnits.addAll(chooser.getSelected(false));
}
}
if (getFirstSelectedTerritory() == null) {
setFirstSelectedTerritory(t);
m_mouseSelectedPoint = me.getMapPoint();
m_mouseCurrentPoint = me.getMapPoint();
enableCancelButton();
}
if (!getFirstSelectedTerritory().equals(t)) {
throw new IllegalStateException("Wrong selected territory");
}
// add all
if (me.isShiftDown()) {
// prevent units of multiple owners from being chosen in edit mode
final CompositeMatch<Unit> ownedNotFactory = new CompositeMatchAnd<Unit>();
if (!BaseEditDelegate.getEditMode(getData())) {
ownedNotFactory.add(unitsToMoveMatch);
} else if (!m_selectedUnits.isEmpty()) {
ownedNotFactory.add(unitsToMoveMatch);
ownedNotFactory.add(Matches.unitIsOwnedBy(getUnitOwner(m_selectedUnits)));
} else {
ownedNotFactory.add(unitsToMoveMatch);
ownedNotFactory.add(Matches.unitIsOwnedBy(getUnitOwner(t.getUnits().getUnits())));
}
m_selectedUnits.addAll(t.getUnits().getMatches(ownedNotFactory));
} else if (me.isControlDown()) {
m_selectedUnits.addAll(Match.getMatches(units, unitsToMoveMatch));
}
// add one
else {
// best candidate unit for route is chosen dynamically later
// check for alt key - add 1/10 of total units (useful for splitting large armies)
final List<Unit> unitsToMove = Match.getMatches(units, unitsToMoveMatch);
Collections.sort(unitsToMove, UnitComparator.getHighestToLowestMovementComparator());
final int iterCount = (me.isAltDown()) ? s_deselectNumber : 1;
int addCount = 0;
for (final Unit unit : unitsToMove) {
if (!m_selectedUnits.contains(unit)) {
m_selectedUnits.add(unit);
addCount++;
if (addCount >= iterCount) {
break;
}
}
}
}
if (!m_selectedUnits.isEmpty()) {
m_mouseLastUpdatePoint = me.getMapPoint();
final Route route = getRoute(getFirstSelectedTerritory(), t, m_selectedUnits);
// Load Bombers with paratroops
if ((!m_nonCombat || IsParatroopersCanMoveDuringNonCombat(getData())) && isParatroopers(getCurrentPlayer())
&& Match.someMatch(m_selectedUnits,
new CompositeMatchAnd<Unit>(Matches.UnitIsAirTransport, Matches.unitHasNotMoved))) {
final PlayerID player = getCurrentPlayer();
// TODO Transporting allied units
// Get the potential units to load
final CompositeMatch<Unit> unitsToLoadMatch = new CompositeMatchAnd<Unit>();
unitsToLoadMatch.add(Matches.UnitIsAirTransportable);
unitsToLoadMatch.add(Matches.unitIsOwnedBy(player));
unitsToLoadMatch.add(Matches.unitHasNotMoved);
final Collection<Unit> unitsToLoad =
Match.getMatches(route.getStart().getUnits().getUnits(), unitsToLoadMatch);
unitsToLoad.removeAll(m_selectedUnits);
for (final Unit u : s_dependentUnits.keySet()) {
unitsToLoad.removeAll(s_dependentUnits.get(u));
}
// Get the potential air transports to load
final CompositeMatch<Unit> candidateAirTransportsMatch = new CompositeMatchAnd<Unit>();
candidateAirTransportsMatch.add(Matches.UnitIsAirTransport);
candidateAirTransportsMatch.add(Matches.unitIsOwnedBy(player));
candidateAirTransportsMatch.add(Matches.unitHasNotMoved);
candidateAirTransportsMatch.add(Matches.transportIsNotTransporting());
final Collection<Unit> candidateAirTransports =
Match.getMatches(t.getUnits().getMatches(unitsToMoveMatch), candidateAirTransportsMatch);
// candidateAirTransports.removeAll(m_selectedUnits);
candidateAirTransports.removeAll(s_dependentUnits.keySet());
if (unitsToLoad.size() > 0 && candidateAirTransports.size() > 0) {
final Collection<Unit> airTransportsToLoad = getAirTransportsToLoad(candidateAirTransports);
m_selectedUnits.addAll(airTransportsToLoad);
if (!airTransportsToLoad.isEmpty()) {
final Collection<Unit> loadedAirTransports =
getLoadedAirTransports(route, unitsToLoad, airTransportsToLoad, player);
m_selectedUnits.addAll(loadedAirTransports);
final MoveDescription message =
new MoveDescription(loadedAirTransports, route, airTransportsToLoad, s_dependentUnits);
setMoveMessage(message);
}
}
}
updateUnitsThatCanMoveOnRoute(m_selectedUnits, route);
updateRouteAndMouseShadowUnits(route);
} else {
setFirstSelectedTerritory(null);
}
}
public Collection<Unit> getAirTransportsToLoad(final Collection<Unit> candidateAirTransports) {
final Set<Unit> defaultSelections = new HashSet<Unit>();
// prevent too many bombers from being selected
final Match<Collection<Unit>> transportsToLoadMatch = new Match<Collection<Unit>>() {
@Override
public boolean match(final Collection<Unit> units) {
final Collection<Unit> airTransports = Match.getMatches(units, Matches.UnitIsAirTransport);
return (airTransports.size() <= candidateAirTransports.size());
}
};
// Allow player to select which to load.
final UnitChooser chooser = new UnitChooser(candidateAirTransports, defaultSelections, s_dependentUnits,
/* categorizeMovement */true, /* categorizeTransportCost */false, getGameData(), /* allowTwoHit */false,
getMap().getUIContext(), transportsToLoadMatch);
chooser.setTitle("Select air transports to load");
final int option =
JOptionPane.showOptionDialog(getTopLevelAncestor(), chooser, "What transports do you want to load",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, null, null);
if (option != JOptionPane.OK_OPTION) {
return Collections.emptyList();
}
return chooser.getSelected(true);
}
/**
* Allow the user to select what units to load.
* If null is returned, the move should be canceled.
*/
public Collection<Unit> getLoadedAirTransports(final Route route, final Collection<Unit> capableUnitsToLoad,
final Collection<Unit> capableTransportsToLoad, final PlayerID player) {
// Get the minimum transport cost of a candidate unit
int minTransportCost = Integer.MAX_VALUE;
for (final Unit unit : capableUnitsToLoad) {
minTransportCost = Math.min(minTransportCost, UnitAttachment.get(unit.getType()).getTransportCost());
}
final Collection<Unit> airTransportsToLoad = new ArrayList<Unit>();
for (final Unit bomber : capableTransportsToLoad) {
final int capacity = TransportTracker.getAvailableCapacity(bomber);
if (capacity >= minTransportCost) {
airTransportsToLoad.add(bomber);
}
}
// If no airTransports can be loaded, return the empty set
if (airTransportsToLoad.isEmpty()) {
return airTransportsToLoad;
}
final Set<Unit> defaultSelections = new HashSet<Unit>();
// Check to see if there's room for the selected units
final Match<Collection<Unit>> unitsToLoadMatch = new Match<Collection<Unit>>() {
@Override
public boolean match(final Collection<Unit> units) {
final Collection<Unit> unitsToLoad = Match.getMatches(units, Matches.UnitIsAirTransportable);
final Map<Unit, Unit> unitMap = TransportUtils.mapTransportsToLoad(unitsToLoad, airTransportsToLoad);
boolean ableToLoad = true;
for (final Unit unit : unitsToLoad) {
if (!unitMap.keySet().contains(unit)) {
ableToLoad = false;
}
}
return ableToLoad;
}
};
List<Unit> loadedUnits = new ArrayList<Unit>(capableUnitsToLoad);
if (!airTransportsToLoad.isEmpty()) {
// Get a list of the units that could be loaded on the transport (based upon transport capacity)
final List<Unit> unitsToLoad =
TransportUtils.findUnitsToLoadOnAirTransports(capableUnitsToLoad, airTransportsToLoad);
final String title = "Load air transports";
final String action = "load";
loadedUnits = UserChooseUnits(defaultSelections, unitsToLoadMatch, unitsToLoad, title, action);
final Map<Unit, Unit> mapping = TransportUtils.mapTransportsToLoad(loadedUnits, airTransportsToLoad);
for (final Unit unit : mapping.keySet()) {
final Collection<Unit> unitsColl = new ArrayList<Unit>();
unitsColl.add(unit);
final Unit airTransport = mapping.get(unit);
if (s_dependentUnits.containsKey(airTransport)) {
unitsColl.addAll(s_dependentUnits.get(airTransport));
}
s_dependentUnits.put(airTransport, unitsColl);
m_mustMoveWithDetails = MoveValidator.getMustMoveWith(route.getStart(),
route.getStart().getUnits().getUnits(), s_dependentUnits, getData(), player);
}
}
return loadedUnits;
}
private void deselectUnits(List<Unit> units, final Territory t, final MouseDetails me) {