|
ex5-6.cpp - Example 5-6 Friend to the card and deck classes |
// File: ex5-6.cpp - a friend to the 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"};
const int HandSize = 5;
const int DeckSize = 52;
class deck;
class hand
{
private:
int card_no[HandSize];
public:
hand() { }
void dealMe(deck&);
void print(const deck&) const;
};
class card
{
private:
int value;
int suit;
public:
card() { }
void assign(int);
int get_value(void) const { return value;}
int get_suit(void) const { return suit;}
void print(void) const;
friend void hand::print(const deck&) const;
};
void card::assign(int x)
{
value = x % 13;
suit = x % 4;
}
void card::print(void) const
{
cout << value_name[value] << " of " << suit_name[suit] << endl;
}
class deck
{
friend class hand;
private:
card d[DeckSize];
int next_card;
public:
deck(void);
void shuffle(void);
void deal(int=HandSize);
void print(void) const;
};
deck::deck(void)
{
for (int i = 0; i < DeckSize; i++) d[i].assign(i);
next_card = 0;
}
void deck::shuffle(void)
{
int i, k;
card temp;
cout << "I am shuffling the deck\n";
for (i = 0; i < DeckSize; i++)
{
k = rand() % DeckSize;
temp = d[i];
d[i] = d[k];
d[k] = temp;
}
}
void deck::print(void) const
{
int i;
for (i = 0; i < DeckSize; i++) d[i].print();
}
void hand::dealMe(deck& dk)
{
int i;
for (i = 0; i < HandSize; i++) card_no[i] = dk.next_card++;
return;
}
void hand::print(const deck& dk) const
{
int i;
cout << "here is your hand:\n";
for (i = 0; i < HandSize; i++) dk.d[card_no[i]].print();
}
int main (void)
{
deck poker;
poker.shuffle();
poker.print();
hand Joe;
hand Mary;
Joe.dealMe(poker);
Mary.dealMe(poker);
cout << "\nOk, Joe ";
Joe.print(poker);
cout << "\nOk, Mary ";
Mary.print(poker);
return 0;
}
CIS27: Programming in C++ Instructor: Joe Bentley