1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
|
#include <iostream>
#include <stdlib.h>
#include <algorithm>
#include <time.h>
using namespace std;
enum suits { diamond, club, heart, spade };
class Card {
int rank; // rank of card
suits suit; // suit of card
public:
Card(); // initialize a card with default values
Card(suits, int); // initialize a card with given values
// accessors
int getRank() { return rank; } // an in-line function
suits getSuit() { return suit; }
// mutators
void setRank(int rv) { rank = rv; }
void setSuit(suits sv) { suit = sv; }
}; // Card
Card::Card()
{
rank = 1;
suit = spade;
}
Card::Card(suits sv, int rv)
{
rank = rv;
suit = sv;
}
ostream & operator<<(ostream & out, Card aCard)
{
switch (int rank = aCard.getRank()) {
case 1: out << "2"; break;
case 1: out << "3"; break;
case 1: out << "4"; break;
case 1: out << "5"; break;
case 1: out << "6"; break;
case 1: out << "7"; break;
case 1: out << "8"; break;
case 1: out << "9"; break;
case 1: out << "10"; break;
case 1: out << "Jack"; break;
case 11: out << "Queen"; break;
case 12: out << "King"; break;
case 13: out << "Ace"; break;
default: out << rank; }
switch (suits suit = aCard.getSuit()) {
case diamond: out << " of Diamonds"; break;
case spade: out << " of spades"; break;
case heart: out << " of hearts"; break;
case club: out << " of clubs"; break; }
return out;
}
class RandomInteger {
public:
unsigned int operator()(unsigned int);
}; // RandomInteger
unsigned int RandomInteger::operator()(unsigned int max)
{
unsigned int rval = rand();
return rval % max;
} // operator()
RandomInteger randomizer; // global object, often not a good idea!
class Deck {
Card cards[52]; // deck of 52 cards
int topCard; // size of deck
public:
Deck();
// shuffle uses the generic algorithm random_shuffle from STL
void shuffle() { random_shuffle(cards, cards+52, randomizer); }
bool isEmpty() { return topCard <= 0; } // return true if empty
Card draw(); // return next card
}; // Deck
Deck::Deck()
{
topCard = 0;
for (int i = 1; i <= 13; i++) {
Card c1(diamond, i), c2(spade, i), c3(heart, i), c4(club, i);
cards[topCard++] = c1;
cards[topCard++] = c2;
cards[topCard++] = c3;
cards[topCard++] = c4; }
} // constructor
Card Deck::draw()
{
if (!isEmpty())
return cards[--topCard];
else {
Card spadeAce(spade, 1);
return spadeAce;
}
} // draw
| |