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
|
#include <iostream>
#include <string>
#include <stdexcept>
struct Card
{
enum Suit_t { Clubs, Diamonds, Hearts, Spades, None }; // joker == None
Card() = default ;
Card( Suit_t suit, int rank ) : suit(suit), rank(rank) { must_be_valid() ; }
Suit_t get_suit() const { return suit ; }
int get_rank() const { return rank ; }
std::string to_string() const ;
private:
Suit_t suit = None ; // joker
int rank = 0 ; // joker
bool valid() const
{
if( rank == 0 ) return suit == None ;
else return rank > 0 && rank < 14 ;
}
void must_be_valid() const
{
// assert( valid() ) ;
if( !valid() ) throw std::logic_error( "invalid card state " ) ;
}
};
std::string Card::to_string() const
{
must_be_valid() ;
static const std::string suit_name[] = { "Clubs", "Diamonds", "Hearts", "Spades" } ;
if( rank > 1 && rank < 11 ) return std::to_string(rank) + " of " + suit_name[suit] ;
switch(rank)
{
case 1 : return "Ace of " + suit_name[suit] ;
case 11 : return "Jack of " + suit_name[suit] ;
case 12 : return "Queen of " + suit_name[suit] ;
case 13 : return "King of " + suit_name[suit] ;
}
return "Joker" ;
}
bool operator== ( Card a, Card b )
{ return a.get_rank() == b.get_rank() && a.get_suit() == b.get_suit() ; }
bool operator!= ( Card a, Card b ) { return !(a==b) ; }
bool operator< ( Card a, Card b )
{
if( a.get_rank() == 0 ) return false ; // joker is not less than any other card
// this assumes that Clubs < Diamonds < Hearts < Spades
// if suits are the same, then the lower ranked card is less
const int weight_a = a.get_suit() * 100 + a.get_rank() ;
const int weight_b = b.get_suit() * 100 + b.get_rank() ;
return weight_a < weight_b ;
}
bool operator> ( Card a, Card b ) { return b < a ; }
bool operator<= ( Card a, Card b ) { return a==b || a < b ; }
bool operator>= ( Card a, Card b ) { return a==b || a > b ; }
int main()
{
const Card deck[] { {}, { Card::Hearts, 7 }, { Card::Hearts, 6 }, { Card::Diamonds, 7 } } ;
for( Card a : deck ) for( Card b : deck )
{
std::string relop = " > " ;
if( a == b ) relop = " == " ;
else if( a < b ) relop = " < " ;
std::cout << a.to_string() << relop << b.to_string() << '\n' ;
}
}
|