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
|
#include <iostream>
#include <string>
#include <cstdlib>
#include <iterator>
#include <numeric>
#include <algorithm>
#include <random>
#include <ctime>
struct card
{
static const int NUM_SUITS = 4;
static const int CARDS_PER_SUIT = 13;
static const int NUM_CARDS = NUM_SUITS * CARDS_PER_SUIT ;
// http://en.cppreference.com/w/cpp/numeric/math/abs
card( int n = 0 ) : number( std::abs(n) % NUM_CARDS ) {}
int number ; // 0 - 51
std::string suit() const
{
static const std::string suit_str[CARDS_PER_SUIT] = { "Clubs", "Diamonds", "Hearts", "Spades" } ;
return suit_str[number/CARDS_PER_SUIT] ;
}
int value() const { return number%CARDS_PER_SUIT ; } // 0 - 12
std::string str() const
{
static const std::string value_str[CARDS_PER_SUIT] = { "Ace", "Two", "Three", "Four", "Five",
"Six", "Seven", "Eight", "Nine",
"Ten", "Jack", "Queen", "King" } ;
return value_str[ value() ] + " of " + suit() ;
}
};
struct deck_of_cards
{
// http://en.cppreference.com/w/cpp/algorithm/iota
// http://en.cppreference.com/w/cpp/iterator/begin
deck_of_cards() { std::iota( std::begin(cards), std::end(cards), 0 ) ; }
void shuffle()
{
// http://en.cppreference.com/w/cpp/header/random
static std::mt19937 rng( std::time(nullptr) ) ;
// http://en.cppreference.com/w/cpp/algorithm/random_shuffle
std::shuffle( std::begin(cards), std::end(cards), rng ) ;
}
bool empty() const { return next == card::NUM_CARDS ; }
card draw()
{
if( empty() ) next = 0 ;
return cards[ next++ ] ;
}
card cards[card::NUM_CARDS] ;
std::size_t next = 0 ;
};
int main()
{
deck_of_cards deck ;
deck.shuffle() ;
int score_1 = 0 ;
int score_2 = 0 ;
while( !deck.empty() )
{
const card c1 = deck.draw() ;
std::cout << "player 1 drew " << c1.str() << '\n' ;
const card c2 = deck.draw() ;
std::cout << "player 2 drew " << c2.str() << '\n' ;
if( c1.suit() == c2.suit() )
{
std::cout << "The hand is a draw!\n\n" ;
++score_1 ;
++score_2 ;
}
else if( c1.suit() < c2.suit() )
{
std::cout << "Player 2 wins the hand.\n\n" ;
score_2 += 2 ;
}
else
{
std::cout << "Player 1 wins the hand.\n\n" ;
score_1 += 2 ;
}
}
std::cout << "\n----------------------------------\n"
<< "Player 1 score: " << score_1 << '\n'
<< "Player 2 Score: " << score_2 << "\n\n";
}
|