Saturday, June 18, 2016

Design OO features of a Deck of Card Game [CCIB]

Design the data structure for a generic deck of cards. How you would subclass it to implement particular card games?



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).
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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