Generating a Deck of Cards

前端 未结 12 906
暖寄归人
暖寄归人 2020-12-09 06:20

I\'m trying to make a simple blackjack program. Sadly, I\'m having problems right off the bat with generating a deck of cards.

#include 
#inc         


        
12条回答
  •  眼角桃花
    2020-12-09 06:49

    The way you model it really depends on what you're trying to do.

    Are you creating an actual game, and the data structures just need to support the gameplay?

    If so, I'd create a card class, with an enum field for the suit and a numeric type (with values 1 - 13) for the face value.

    On the other hand, if you're building an analysis application or an AI player, then the model might be a little bit different.

    A few years ago, I wrote a simulator to calculate probabilities in various Texas Holdem scenarios, and I wanted it to crunch numbers REALLY quickly. I started out with a very straightforward model (card class, suit enum, etc) but after a lot of profiling and optimization, I ended up with a bitwise representation.

    Each card was a sixteen-bit value, with the thirteen high-order bits representing the face value, the two low order bits representing the suit, and with bit[2] as a special flag indicating an ace (used only in cases where the ace might appear in an A2345 straight).

    Here are a few examples:

    0000000000001001  <----  Two of hearts
    0100000000000011  <----  King of spades
    1000000000000110  <----  Ace of diamonds
    
    ^^^^^^^^^^^^^            ("face-value" bits)
                 ^           ("low-ace" flag)
                  ^^         ("suit" bits)
    

    You can imagine how, with a design like this, it's lighting fast to look for pairs, threes-of-a-kind, and straights (flushes are slightly more tricky).

    I won't go into all the particular operations, but suffice it to say that this kind of model supports millions of operations per second...

    Of course, keep in mind, I'm not actually advocating that you use a design like this in a straightforward game implementation. The only reason I ended up with this design is because I needed to conduct massive statistical simulations.

    So think carefully about how you want to model:

    • Each card
    • A player's hand
    • The entire deck
    • The state of the table... including all player hands (including players who have split their initial hand), maybe a six-deck shoe, the discard pile, etc

    The overall application model, and the goals of the application in general, will determine to a large extent the types of data structures that'll be most appropriate.

    Have fun!!!

提交回复
热议问题