一个简单的C代码,模拟洗牌发牌

一个用指针、结构体,数组实现的高效的模拟洗牌发牌程序:

#include 
#include 
#include 

//card structure definition//
struct card
{
        const char *face;
        const char *suit;
};//end structure card

typedef struct card Card;//new type name for struct card

//prototypes
void fillDeck( Card * const wDeck, const char * wFace[], const char * wSuit[] );
void shuffle( Card * const wDeck );
void deal( const Card * const wDeck );

int main( void )
{
        Card deck[ 52 ];//define array of Cards
        
        //initialize array of pointers
        const char *face[] = {"A", "2", "3", "4", "5",
                "6", "7", "8", "9", "10", "J", "Q", "K" };
        //initialize array of pointers
        const char *suit[] = { "红桃", "方块", "黑桃", "梅花" };

        srand( time( NULL ) );        //randomize

        fillDeck( deck, face, suit );//load the deck with Cards
        shuffle( deck );//put Cards in random order
        deal( deck );//deal all 52 Cards

        return 0;
}//end main

//place strings into Card structures
void fillDeck( Card * const wDeck, const char * wFace[], const char * wSuit[] )
{
        int i;

        for ( i = 0; i<=51; i++ )
        {
                wDeck[ i ].face = wFace[ i % 13 ];
                wDeck[ i ].suit = wSuit[ i / 13 ];
        }
}//end function fillDeck

//shuffle cards
void shuffle( Card * const wDeck )
{
        int i;
        int j;//variable to hold random value between 0 - 51
        Card temp;//define temporary structure for swapping Cards

        for ( i = 0; i <=51; i++ )
        {
                j = rand() % 52;
                temp = wDeck[ i ];
                wDeck[ i ] = wDeck[ j ];
                wDeck[ j ] = temp;
        }
}//end function shuffle

//deal cards
void deal( const Card * const wDeck )
{
        int i;

        for ( i = 0; i <= 51; i++ )
        {
                printf( "%5s %-8s%c", wDeck[ i ].face, wDeck[ i ].suit, ( i + 1 ) % 2 ? '\t' : '\n' );

        }
}


你可能感兴趣的:(一个简单的C代码,模拟洗牌发牌)