// Phil Ottewell's STL Course - http://www.pottsoft.com/home/stl/stl.htmlx // // Example 3.2 © Phil Ottewell 1997 // // Purpose: // Demonstrate deque sequence container with a dumb card game // which is a bit like pontoon/blackjack/vingt-et-un // Note sneaky use of random_shuffle() sequence modifying agorithm // ANSI C Headers #include // C++ STL Headers #include #include #include #ifdef _WIN32 using namespace std; #endif class Card { public: Card() { Card(1,1); } Card( int s, int c ) { suit = s; card = c; } friend ostream & operator<<( ostream &os, const Card &card ); int value() { return( card ); } private: int suit, card; }; ostream & operator<<( ostream &os, const Card &card ) { static const char *suitname[] = { "Hearts", "Clubs", "Diamonds", "Spades" }; static const char *cardname[] = { "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King" }; return( os << cardname[card.card-1] << " of " << suitname[card.suit] ); } class Deck { public: Deck() { newpack(); }; void newpack() { for ( int i = 0; i < 4; ++i ) { for ( int j = 1; j <= 13; ++j ) cards.push_back( Card( i, j ) ); } } // shuffle() uses the STL sequence modifying algorithm, random_shuffle() void shuffle() { random_shuffle( cards.begin(), cards.end() ); } bool empty() const { return( cards.empty() ); } Card twist() { Card next = cards.front(); cards.pop_front(); return(next); } private: deque< Card > cards; }; int main( int argc, char *argv[] ) { Deck deck; Card card; int total, bank_total; char ch; // End of declarations ... while ( 1 ) { cout << "\n\n ---- New deck ----" << endl; total = bank_total = 0; deck.shuffle(); ch = 'T'; while ( 1 ) { if ( total > 0 && total != 21 ) { cout << "Twist or Stick ? "; cin >> ch; if ( !cin.good() ) cin.clear(); // Catch Ctrl-Z ch = toupper( ch ); } else { if ( total == 21 ) ch = 'S'; // Stick at 21 } if ( ch == 'Y' || ch == 'T' ) { card = deck.twist(); total += card.value(); cout << card << " makes a total of " << total << endl; if ( total > 21 ) { cout << "Bust !" << endl; break; } } else { cout << "You stuck at " << total << "\n" << "Bank tries to beat you" << endl; while ( bank_total < total ) { if ( !deck.empty() ) { card = deck.twist(); bank_total += card.value(); cout << card << " makes bank's total " << bank_total << endl; if ( bank_total > 21 ) { cout << "Bank has bust - You win !" << endl; break; } else if ( bank_total >= total ) { cout << "Bank has won !" << endl; break; } } } break; } } cout << "New game [Y/N] ? "; cin >> ch; if ( !cin.good() ) cin.clear(); // Catch Ctrl-Z ch = toupper( ch ); if ( ch != 'Y' && ch != 'T' ) break; deck.newpack(); } return( EXIT_SUCCESS ); }