< Previous | Contents | Next >
After some initial statements, I define the Card class for an individual playing card.
//Blackjack
//Plays a simple version of the casino game of blackjack; for 1 - 7 players
#include <iostream> #include <string> #include <vector> #include <algorithm>
362 Chapter 10 n Inheritance and Polymorphism: Blackjack
#include <ctime>
using namespace std; class Card
{
public:
enum rank {ACE = 1, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING};
enum suit {CLUBS, DIAMONDS, HEARTS, SPADES};
//overloading << operator so can send Card object to standard output friend ostream& operator<<(ostream& os, const Card& aCard);
Card(rank r = ACE, suit s = SPADES, bool ifu = true);
//returns the value of a card, 1 - 11 int GetValue() const;
//flips a card; if face up, becomes face down and vice versa void Flip();
private:
rank m_Rank; suit m_Suit; bool m_IsFaceUp;
};
Card::Card(rank r, suit s, bool ifu): m_Rank(r), m_Suit(s), m_IsFaceUp(ifu)
{}
int Card::GetValue() const
{
//if a cards is face down, its value is 0 int value = 0;
if (m_IsFaceUp)
{
//value is number showing on card value = m_Rank;
//value is 10 for face cards if (value > 10)
Introducing the Blackjack Game 363
{
value = 10;
}
}
return value;
}
void Card::Flip()
{
m_IsFaceUp = !(m_IsFaceUp);
I define two enumerations, rank and suit, to use as the types for the rank and suit data members of the class, m_Rank and m_Suit. This has two benefits. First, it makes the code more readable. A suit data member will have a value like CLUBS or HEARTS instead of 0 or 2. Second, it limits the values that these two data members can have. m_Suit can only store a value from suit, and m_Rank can only store a value from rank.
Next, I make the overloaded operator<<() function a friend of the class so I can display a card object on the screen.
GetValue() returns a value for a Card object, which can be between 0 and 11. Aces are valued at 11. (I deal with potentially counting them as 1 in the Hand class, based on the other cards in the hand.) A face-down card has a value of 0.