Playing Cards

posted by: Ms. Martin 17 February 2011 No Comment

Thanks to Owen Astrachan from Duke University!

You will write some methods involving card decks and cards that implement useful Java interfaces.  This should give you practice reading code as well as a better sense of why interfaces are important.  Take a look at the Comparable interface and the Iterator interface.  What classes do we know that implement them?  What does that mean?

Save the Deck class somewhere but don’t open it.  Also save the ICard interface which is defined as follows:

public interface ICard {
	public static final int SPADES = 0;
	public static final int HEARTS = 1;
	public static final int DIAMONDS = 2;
	public static final int CLUBS = 3;

	public int getSuit();
	public int getRank();
}

Knowing that Card implements ICard and Deck implements Iterator should be enough for you to write the following methods — you don’t need to look into Deck at all.

Note that when you get a Card from a Deck, you have to cast it since the .next() method required by Iterator returns an Object:

Deck d = new Deck();
ICard c1 = (ICard)d.next();

Define the following static methods:
1. isRed returns true if its ICard parameter is red (hearts or diamonds) and returns false otherwise.
public boolean isRed(ICard card){…}

2. isPair returns true if its two ICard parameters represent a pair and returns false otherwise.
public boolean isPair(ICard a, ICard b){…} A pair is two cards of the same rank (e.g., two kings or two eights).

3. isFlush returns true if the array of cards is a flush and returns false otherwise. A flush is a hand, say in poker, in which all the cards have the same suit (e.g., five hearts, or five clubs for a five-card hand).
public boolean isFlush(ICard[] hand){…}

4. handTotal, which returns the total value of a hand. In blackjack or 21, the value of a hand is the total of the cards, where jacks, queens, and kings (11, 12, and 13, respectively, as returned by getRank()) each count as 10, and an ace counts as 1 or 10, whichever is better. A total over 21 is a bust; it’s not good to bust.
public int handTotal(ICard[] hand){…}

One of the values of interfaces is that they allow for collaboration.  Explain to yourself why that is.

1 Star2 Stars3 Stars4 Stars5 Stars (9 votes, average: 2.33 out of 5)
Loading ... Loading ...

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>