Java Reference
In-Depth Information
The default constructor generated by the compiler will create a
Hand
object containing an empty
Stack
member,
hand
. The
add()
member will add the
Card
object passed as an argument by
pushing it onto the
hand
. We also have implemented a
toString()
method here. We obtain an
iterator to traverse the cards in the hand, and construct a string representation of the complete hand.
Note that we should not use the
pop()
method here, because it removes an object from the stack, so
using it here would remove all the cards from the hand.
We might well want to compare hands in general, but this is completely dependent on the context. The
best approach to accommodate this when required would be to derive a game-specific class from
Hand
- a
PokerHand
class for instance - and make it implement its own version of the
compareTo()
method in the
Comparable
interface.
The last class we need will represent a deck of cards, and will also deal a hand:
import java.util.*;
class CardDeck {
// Create a deck of 52 cards
public CardDeck() {
for(int theSuit = Card.HEARTS; theSuit<= Card.SPADES; theSuit++)
for(int theValue = Card.ACE; theValue <= Card.KING; theValue++)
deck.push(new Card(theValue, theSuit));
}
// Deal a hand
public Hand dealHand(int numCards) {
Hand hand = new Hand();
for(int i = 0; i<numCards; i++)
hand.add((Card)deck.pop());
return hand;
}
private Stack deck = new Stack();
}
The card deck is stored as a
Stack
object,
deck
. In the constructor, the nested
for
loops create the
cards in the deck. For each suit in turn, we generate all the
Card
objects from ace to king and push
them onto the
Stack
object,
deck
.
The
dealHand()
method creates a
Hand
object, and then pops
numCards
objects off the deck stack
and adds each of them to
hand
. The
Hand
object is then returned. At the moment our deck is
completely sequenced. We need a method to shuffle the deck:
class CardDeck {
// Shuffle the deck
public void shuffle() {
Collections.shuffle(deck);
}
// Rest of the class as before...
}