]>
wirehaze git hosting - solitaire.git/blob - src/solitaire/Depot.java
3 import java
.util
.LinkedList
;
5 import java
.util
.Optional
;
6 import java
.util
.stream
.Collectors
;
9 private final List
<Card
> cards
;
11 Depot(List
<Card
> cards
) {
13 throw new IllegalArgumentException("Depot should be initialized with at least one card");
15 this.cards
= new LinkedList
<>(cards
);
16 this.cards
.getLast().reveal();
19 private static boolean isValidNextCard(Card lastCard
, Card nextCard
) {
20 if (nextCard
.getSuit().isRed() == lastCard
.getSuit().isRed())
23 return lastCard
.getRank().isSuccessorOf(nextCard
.getRank());
26 private boolean isValidPlacement(Card card
) {
28 return card
.getRank() == Rank
.KING
;
30 return isValidNextCard(cards
.getLast(), card
);
33 private static boolean isValidRun(List
<Card
> run
) {
36 for (Card next
: run
) {
37 if (next
.isHidden() || (prev
!= null && !isValidNextCard(prev
, next
)))
46 boolean add(List
<Card
> run
) {
48 * no invalid run can be generated by the game, so we only need to check
51 if (!isValidPlacement(run
.getFirst()))
58 boolean add(Card card
) {
59 return add(List
.of(card
));
62 Optional
<List
<Card
>> remove(int size
) {
64 throw new IllegalArgumentException("Size must be a positive integer");
66 if (cards
.size() < size
)
67 return Optional
.empty();
69 List
<Card
> slice
= cards
.subList(cards
.size() - size
, cards
.size());
71 if (!isValidRun(slice
))
72 return Optional
.empty();
74 List
<Card
> run
= List
.copyOf(slice
);
78 cards
.getLast().reveal();
80 return Optional
.of(run
);
84 public String
toString() {
88 return cards
.stream().map(String
::valueOf
).collect(Collectors
.joining("\n"));