/* * Card shuffling program * By Dan Gookin * 1/31/97 */ #include #include #include #define DECK 52 //Cards in a deck #define HEARTS 0x03 //Heart character #define DIAMONDS 0x04 //Diamond char. #define CLUBS 0x05 //Clubs character #define SPADES 0x06 //Spade char. int draw_card(void); void shuffle(void); int rnd(int range); void seedrnd(void); /* * The cards array is stuck out here in no-man's land * to make it available to both the shuffle and * draw_card functions */ int cards[DECK]; //Deck of Cards void main() { int x=DECK; int card; char c,s; puts("Card shuffling demonstration program"); shuffle(); /* * Sift through the entire deck, decrementing * variable x from 52 down to zero. * * Start by drawing the card, one for each loop. * * The card%13 math converts the random number from * 1 to 52 into chunks of 0 to 12 -- like the cards * in a suit. The +1 makes the numbers 1 through 13 * * The switch-case structure weeds out the Ace, Ten * Jack, Queen and King, setting their characters in the * c variable; * The (card%13)+'1' sets the remaining characters equal * to 2 through 9; adding them to the character '1' which, * according to the ASCII table from Volume I, works * out just fine */ while(x--) { card = draw_card(); switch((card % 13) + 1) { case(1): c = 'A'; break; case(10): c = 'T'; break; case(11): c = 'J'; break; case(12): c = 'Q'; break; case(13): c = 'K'; break; default: c = (card%13)+'1'; } /* * A complex if-else structure handles the suits, dividing * the values up into four chunks. This sets the s * char varaible equal to the characters for Hearts, * Diamonds, etc. * * The final printf displays the values */ if(card>=0 && card<=13) s = HEARTS; else if(card>=14 && card<=26) s = DIAMONDS; else if(card>=27 && card<=40) s = CLUBS; else s = SPADES; printf("%c%c\t",c,s); /* * This little gem is for formatting only. You divide * x (the loop counter) by four -- X MOD 4. When the * result is zero, a new line is printed. The ! (not) * reverses the results of the MOD; otherwise the * newline would print three times in a row */ if(!(x%4)) putchar('\n'); } } /* * The draw_card routine returns a random * number from 1 to 52 for each card in the deck * It never returns the same card twice as long * as you call the shuffle routine -- just * like real life! */ int draw_card(void) { int card; do { card=rnd(DECK); //draw card } while(cards[card]); //is card drawn? cards[card]=1; //mark it as drawn return(card+1); //make it 1 to 52 } /* * The shuffle routine does two things: * It initializes the randomizer and * It initializes the cards[] array */ void shuffle(void) { int x; seedrnd(); for(x=0;x