1 /* 2 * Copyright (c) 1980 Regents of the University of California. 3 * All rights reserved. 4 * 5 * Redistribution and use in source and binary forms are permitted 6 * provided that this notice is preserved and that due credit is given 7 * to the University of California at Berkeley. The name of the University 8 * may not be used to endorse or promote products derived from this 9 * software without specific prior written permission. This software 10 * is provided ``as is'' without express or implied warranty. 11 */ 12 13 #ifndef lint 14 static char sccsid[] = "@(#)cards.c 5.2 (Berkeley) 03/10/88"; 15 #endif /* not lint */ 16 17 #include <stdio.h> 18 #include "deck.h" 19 20 21 /* 22 * initialize a deck of cards to contain one of each type 23 */ 24 25 makedeck( d ) 26 27 CARD d[]; 28 { 29 register int i, j, k; 30 long time(); 31 32 i = time( (long *) 0 ); 33 i = ( (i&0xff) << 8 ) | ( (i >> 8)&0xff ) | 1; 34 srand( i ); 35 k = 0; 36 for( i = 0; i < RANKS; i++ ) { 37 for( j = 0; j < SUITS; j++ ) { 38 d[k].suit = j; 39 d[k++].rank = i; 40 } 41 } 42 } 43 44 45 46 /* 47 * given a deck of cards, shuffle it -- i.e. randomize it 48 * see Knuth, vol. 2, page 125 49 */ 50 51 shuffle( d ) 52 53 CARD d[]; 54 { 55 register int j, k; 56 CARD c; 57 58 for( j = CARDS; j > 0; --j ) { 59 k = ( rand() >> 4 ) % j; /* random 0 <= k < j */ 60 c = d[j - 1]; /* exchange (j - 1) and k */ 61 d[j - 1] = d[k]; 62 d[k] = c; 63 } 64 } 65 66 67 68 /* 69 * return true if the two cards are equal... 70 */ 71 72 eq( a, b ) 73 74 CARD a, b; 75 { 76 return( ( a.rank == b.rank ) && ( a.suit == b.suit ) ); 77 } 78 79 80 81 /* 82 * isone returns TRUE if a is in the set of cards b 83 */ 84 85 isone( a, b, n ) 86 87 CARD a, b[]; 88 int n; 89 { 90 register int i; 91 92 for( i = 0; i < n; i++ ) { 93 if( eq( a, b[i] ) ) return( TRUE ); 94 } 95 return( FALSE ); 96 } 97 98 99 100 /* 101 * remove the card a from the deck d of n cards 102 */ 103 104 remove( a, d, n ) 105 106 CARD a, d[]; 107 int n; 108 { 109 register int i, j; 110 111 j = 0; 112 for( i = 0; i < n; i++ ) { 113 if( !eq( a, d[i] ) ) d[j++] = d[i]; 114 } 115 if( j < n ) d[j].suit = d[j].rank = EMPTY; 116 } 117 118 119 120 /* 121 * sorthand: 122 * Sort a hand of n cards 123 */ 124 sorthand(h, n) 125 register CARD h[]; 126 int n; 127 { 128 register CARD *cp, *endp; 129 CARD c; 130 131 for (endp = &h[n]; h < endp - 1; h++) 132 for (cp = h + 1; cp < endp; cp++) 133 if ((cp->rank < h->rank) || 134 (cp->rank == h->rank && cp->suit < h->suit)) { 135 c = *h; 136 *h = *cp; 137 *cp = c; 138 } 139 } 140 141