|
ex5-7.cpp - Example 5-7 More friendly poker |
// File: ex5-7.cpp
#include <iostream>
#include <cstdlib> // needed for rand() function
#include <cstring>
#include <cassert>
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
{
friend void threeOrFourOfAKind(const deck& d,const hand&);
public:
hand(void);
~hand();
void dealMe(deck&);
void print(const deck&) const;
char* getName(void) const {return name;}
private:
char* name;
int card_no[HandSize];
};
hand::hand(void)
{
char temp[32];
cout << "Enter player name => ";
cin >> temp;
name = new char[strlen(temp) + 1];
strcpy(name,temp);
}
hand::~hand()
{
delete [] name;
}
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;
};
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 void threeOrFourOfAKind(const deck&,const hand&);
friend class hand;
public:
deck();
void print(void) const;
private:
card d[DeckSize];
int next_card;
void shuffle(void);
};
deck::deck()
{
int i;
for (i = 0; i < DeckSize; i++) d[i].assign(i);
next_card = 0;
shuffle();
}
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;
assert(dk.next_card < DeckSize-4);
for (i = 0; i < HandSize; i++) card_no[i] = dk.next_card++;
}
void hand::print(const deck& dk) const
{
int i;
for (i = 0; i < HandSize; i++) dk.d[card_no[i]].print();
}
int main (void)
{
deck poker;
hand player[3];
int i;
for (i = 0; i < 3; i++) player[i].dealMe(poker);
for (i = 0; i < 3; i++)
{
cout << "\nOk "<<(player[i].getName()) <<", here is your hand\n";
player[i].print(poker);
threeOrFourOfAKind(poker,player[i]);
}
return 0;
}
void threeOrFourOfAKind(const deck& dk,const hand& who)
{
int temp;
int card_count;
for (int i = 0; i < 3; i++)
{
card_count = 1;
temp = (dk.d[who.card_no[i]]).get_value();
for (int j = i + 1; j < HandSize; j++)
if (temp == dk.d[who.card_no[j]].get_value()) card_count++;
if (card_count > 2)
{
cout << "Hey, " <<(who.getName()) <<", you have " << card_count
<< ' ' << value_name[temp] << "s.\n";
return;
}
}
return;
}
CIS27: Programming in C++ Instructor: Joe Bentley