-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathCards.java
More file actions
61 lines (47 loc) · 1.47 KB
/
Cards.java
File metadata and controls
61 lines (47 loc) · 1.47 KB
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
package blackjack.domain.card;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Cards {
private static final int BLACK_JACK = 21;
private final List<Card> cards;
public Cards() {
this.cards = new ArrayList<>();
}
public void receiveCard(final Card card) {
cards.add(card);
}
public List<Card> toList() {
return Collections.unmodifiableList(cards);
}
public int calculateCards() {
final int sumOfCards = getSumOfCards();
final int aceCount = getAceCount();
if (sumOfCards > BLACK_JACK && aceCount > 0) {
return getBestSumWithAce(sumOfCards);
}
return sumOfCards;
}
private int getAceCount() {
return (int) cards.stream()
.filter(card -> card.getCardType().isAce())
.count();
}
private int getSumOfCards() {
return cards.stream()
.map(Card::getCardType)
.mapToInt(CardType::getPoint)
.sum();
}
private int getBestSumWithAce(final int sum) {
final int lowerAcePoint = CardType.ACE.getLowerAcePoint();
final int higherAcePoint = CardType.ACE.getPoint();
int aceCount = getAceCount();
int totalPoint = sum;
while (aceCount > 0 && totalPoint > BLACK_JACK) {
totalPoint = totalPoint - higherAcePoint + lowerAcePoint;
aceCount--;
}
return totalPoint;
}
}