Monday, March 16, 2015

Design a deck of cards

This is a traditional OOD problem. To start, a card has two elements: the suit, and the value. So we will have an enum class Suit, which contains CLUBS, SPADES, HEARTS and DIAMONDS. We will also have an integer value, cardValue to represent the value of the card (1 - 13).


public class Card{
 public enum Suit{
  CLUBS (1), SPADES (2), HEARTS (3), DIAMONDS (4);
  private Suit(int v) { value = v;}
 };
 private int cardValue;
 private Suit suit;
 public Card(int r, Suit s){
  cardValue = r;
  suit = s;
 }
 public int value() { return card };
 public Suit suit() { return suit };
}


Now if we want to build a blackjack game, we need to know the value of cards. Face cards are 10 and an ace is 11. So we need to extend the above class and override the the value() method.


public class BlackJackCard extends Card {
 public BlackJackCard(int r, Suit s) { super(r, s);}
 public int value() {
  int r = super.value();
  if(r == 1)
   return 11;//ace is 11
  if(r < 10)
   return r;
  return 10;
 }
}
boolean isAce(){
   return super.value() == 1;
}

No comments:

Post a Comment