Java Reference
In-Depth Information
public Hand dealHand(int numCards) {
if(deck.size() < numCards) {
System.err.println("Not enough cards left in the deck!");
System.exit(1);
}
Hand hand = new Hand();
for(int i = 0 ; i < numCards ; ++i) {
hand.add(deck.pop());
}
return hand;
}
private Stack<Card> deck = new Stack<>();
}
Directory "TryDeal"
The card deck is stored as a Stack<Card> object, deck . In the constructor, the nested for loops create
the cards in the deck. For each suit in turn, you generate all the Card objects for each rank and push them
onto the Stack<> object, deck . The values() method for an enum type returns a collection containing
all the enum constants so that's how the loop iterates over all possible suits and ranks.
The dealHand() method creates a Hand object, and then pops numCards Card objects off the deck stack
and adds each of them to hand . The Hand object is then returned. At the moment your deck is completely
sequenced. You need a method to shuffle the deck before you deal:
import java.util.Stack;
import java.util.Collections;
public class CardDeck {
// Shuffle the deck
public void shuffle() {
Collections.shuffle(deck);
}
// Rest of the class as before...
}
Directory "TryDeal"
With the aid of another static parameterized method from the Collections class it couldn't be easier.
The shuffle() method in Collections shuffles the contents of any collection that implements the
List<> interface. The Stack<> class implements List<> so you can use the shuffle() method to pro-
duce a shuffled deck of Card objects. For those interested in the details of shuffling, this shuffle()
method randomly permutes the list by running backward through its elements swapping the current ele-
ment with a randomly chosen element between the first and the current element. The time taken to com-
plete the operation is proportional to the number of elements in the list.
Search WWH ::




Custom Search