forked from AllenDowney/ThinkJavaCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenius.java
More file actions
66 lines (59 loc) · 1.87 KB
/
Genius.java
File metadata and controls
66 lines (59 loc) · 1.87 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
public class Genius extends Player {
/**
* Constructs Genius using Player constructor.
*/
public Genius(String name) {
super(name);
}
/**
* 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) {
int[] indexWorks = new int[getHand().size()];
//Searches for an 8 first, since these cost the most points at the end of the game.
for (int i = 0; i < getHand().size(); i++) {
Card card = getHand().getCard(i);
if (card.getRank() == 8) {
return getHand().popCard(i);
}
}
//Searches for the highest rank that works.
Card chosenCard = new Card(0, 0);
int index = -1;
for (int i = 0; i < getHand().size(); i++) {
Card card = getHand().getCard(i);
if (cardMatches(card, prev) && card.getRank() > chosenCard.getRank()) {
chosenCard = card;
index = i;
}
}
if (index != -1) {
return getHand().popCard(index);
} else {
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(getName() + " draws " + card);
if (cardMatches(card, prev)) {
return card;
}
getHand().addCard(card);
}
}
}