forked from AllenDowney/ThinkJavaCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlayer.java
More file actions
118 lines (106 loc) · 2.56 KB
/
Player.java
File metadata and controls
118 lines (106 loc) · 2.56 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
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
/**
* A player in a game of crazy eights.
*/
public class Player {
private String name;
private Hand hand;
/**
* Constructs a player with an empty hand.
*/
public Player(String name) {
this.name = name;
this.hand = new Hand(name);
}
/**
* Gets the player's name.
*/
public String getName() {
return name;
}
/**
* Gets the player's hand.
*/
public Hand getHand() {
return hand;
}
/**
* Removes and returns a legal card from the player's hand.
*/
public Card play(Eights eights, Card prev) {
Card card = searchForMatch(prev);
if (card == null) {
card = drawForMatch(eights, prev);
}
return card;
}
/**
* Searches the player's hand for a matching card.
*/
public Card searchForMatch(Card prev) {
for (int i = 0; i < hand.size(); i++) {
Card card = hand.getCard(i);
if (cardMatches(card, prev)) {
return hand.popCard(i);
}
}
return null;
}
/**
* Draws cards until a match is found.
*/
public Card drawForMatch(Eights eights, Card prev) {
while (true) {
Card card = eights.draw();
System.out.println(name + " draws " + card);
if (cardMatches(card, prev)) {
return card;
}
hand.addCard(card);
}
}
/**
* Checks whether two cards match.
*/
public static boolean cardMatches(Card card1, Card card2) {
if (card1.getSuit() == card2.getSuit()) {
return true;
}
if (card1.getRank() == card2.getRank()) {
return true;
}
if (card1.getRank() == 8) {
return true;
}
return false;
}
/**
* Calculates the player's score (penalty points).
*/
public int score() {
int sum = 0;
for (int i = 0; i < hand.size(); i++) {
Card card = hand.getCard(i);
int rank = card.getRank();
if (rank == 8) {
sum -= 20;
} else if (rank > 10) {
sum -= 10;
} else {
sum -= rank;
}
}
return sum;
}
/**
* Displays the player's hand.
*/
public void display() {
hand.display();
}
/**
* Displays the player's name and score.
*/
public void displayScore() {
System.out.println(name + " has " + score() + " points");
}
}