Interfacing with playing cards Download

Christina Cacioppo

compareTo, classes, inheritance Idea sketch


Introduction

In order for my cards to work with your cards, they've got to be the same type of cards. How do we pull that off? With an interface, which is a simple way for students to use an object – in this case, a card – without needing to know how it's implemented or works.

The iCard interface specifies the behavior of the card without providing information about how cards are implemented:

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

    // returns a value like ICard.SPADES
    public int getSuit();

    // returns a value between 1 (ace) and 13 (king)
    public int getRank();
}

The ICard interface specifies the behavior of cards without providing information about their implementation. That's enough for us to do things with them like, for example, tell us if a list of cards is sorted:

public boolean isSorted(ICard[] deck){
    for(int i = 1; i < deck.length; i++){
        if(deck[i - 1].compareTo(deck[k]) > 0){
            return false;
        }
    }
    return true;
}


Task

Use the ICard interface to write:

  1. A function isBlack that returns true if the card parameter is black (spades or clubs) and false otherwise:

    public boolean isRead(ICard card){ ... }

  2. In poker, a pair is two cards of the same rank, like two 2s or two Kings. Write isPair, a function that returns true if its two ICard parameters represent a pair and false otherwise.

    public boolean isPair(ICard first, ICard second){ ... }

  3. A straight is a set of cards that contains five cards of sequential rank in at least two different suits, like 10♣, 9♠, 8♦, 7♣, 6♥. Write a function isStraight that returns true if the hand contains a straight and false if it doesn't.

    public boolean isStraight(ICard[] hand){ ... }

  4. In Blackjack, the value of a hand is the total of the cards. Aces count for either 1 or 10, whichever is more advantagenous, and face cards (jacks, queens, and kings) are “worth” their getRank() value. (So: 11, 12, and 13 respectively.) Write the handTotal function that returns the total value of a hand.

    public int handTotal(ICard[] hand){ ... }


Starter code

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

    // returns a value like ICard.SPADES
    public int getSuit();

    // returns a value between 1 (ace) and 13 (king)
    public int getRank();
}

Useful tools to solve the problem