ex3-7.cpp - Example 3-7 The card and deck classes

// File: ex3-7.cpp - card and deck classes

#include <iostream>
#include <cstdlib>	// needed for rand() function
using namespace std;

const char* value_name[13] = {"two","three","four","five","six",
	"seven","eight","nine","ten","jack","queen","king","ace"};
const char* suit_name[4] = {"clubs","diamonds","hearts","spades"};

class card
{
  private:
	 int value;
	 int suit;
  public:
	 void assign(int);
	 int get_value(void) const; 	// accessor function
	 int get_suit(void) const; 	// accessor function
	 void print(void) const;
};

int card::get_value(void) const
{
  return value;
}
int card::get_suit(void) const
{
  return suit;
}

void card::assign(int x)
{
  value = x % 13;
  suit = x / 13;
  return;
}

void card::print(void) const
{
  cout << (value_name[value]) << " of "
	 << (suit_name[suit]) << endl;
  return;
}


class deck
{
  private:
	 card d[52];
	 int next_card;
  public:
	 void create_deck(void);
	 void shuffle(void);
	 void deal(int=5);
	 void print(void) const;
};

void deck::create_deck(void)
{
  for (int i = 0; i < 52; i++) d[i].assign(i);
  next_card = 0;
  return;
}

void deck::shuffle(void)
{
  int i, k;
  card temp;
  cout << "I am shuffling the deck\n";
  for (i = 0; i < 52; i++)
  {
	 k = rand() % 52;
	 temp = d[i];
	 d[i] = d[k];
	 d[k] = temp;
  }
  return;
}

void deck::print(void) const
{
  cout << "\nHere's the deck:\n";
  for (int i = 0; i < 52; i++) d[i].print();
  return;
}

void deck::deal(int no_of_cards)
{
  cout << "\nOk, I will deal you " << no_of_cards << " cards:\n";
  for (int i = 0; i < no_of_cards; i++)
	 d[next_card++].print();
  return;
}


int main (void)
{
  deck poker;
  poker.create_deck();
  poker.print();
  poker.shuffle();
  poker.print();
  poker.deal();
  poker.deal(3);
  return 0;
}



CIS27: Programming in C++    Instructor: Joe Bentley