xref: /original-bsd/games/cribbage/cards.c (revision d7f3dd14)
1 
2 #include	<stdio.h>
3 #include	"deck.h"
4 
5 
6 /*
7  * initialize a deck of cards to contain one of each type
8  */
9 
10 makedeck( d )
11 
12     CARD	d[];
13 {
14 	register  int		i, j, k;
15 	long			time();
16 
17 	i = time( (long *) 0 );
18 	i = ( (i&0xff) << 8 ) | ( (i >> 8)&0xff ) | 1;
19 	srand( i );
20 	k = 0;
21 	for( i = 0; i < RANKS; i++ )  {
22 	    for( j = 0; j < SUITS; j++ )  {
23 		d[k].suit = j;
24 		d[k++].rank = i;
25 	    }
26 	}
27 }
28 
29 
30 
31 /*
32  * given a deck of cards, shuffle it -- i.e. randomize it
33  * see Knuth, vol. 2, page 125
34  */
35 
36 shuffle( d )
37 
38     CARD	d[];
39 {
40 	register  int		j, k;
41 	CARD			c;
42 
43 	for( j = CARDS; j > 0; --j )  {
44 	    k = ( rand() >> 4 ) % j;		/* random 0 <= k < j */
45 	    c = d[j - 1];			/* exchange (j - 1) and k */
46 	    d[j - 1] = d[k];
47 	    d[k] = c;
48 	}
49 }
50 
51 
52 
53 /*
54  * return true if the two cards are equal...
55  */
56 
57 eq( a, b )
58 
59     CARD		a, b;
60 {
61 	return(  ( a.rank == b.rank )  &&  ( a.suit == b.suit )  );
62 }
63 
64 
65 
66 /*
67  * isone returns TRUE if a is in the set of cards b
68  */
69 
70 isone( a, b, n )
71 
72     CARD		a, b[];
73     int			n;
74 {
75 	register  int		i;
76 
77 	for( i = 0; i < n; i++ )  {
78 	    if(  eq( a, b[i] )   )  return( TRUE );
79 	}
80 	return( FALSE );
81 }
82 
83 
84 
85 /*
86  * remove the card a from the deck d of n cards
87  */
88 
89 remove( a, d, n )
90 
91     CARD		a, d[];
92     int			n;
93 {
94 	register  int		i, j;
95 
96 	j = 0;
97 	for( i = 0; i < n; i++ )  {
98 	    if(  !eq( a, d[i] )  )  d[j++] = d[i];
99 	}
100 	if(  j < n  )  d[j].suit = d[j].rank = EMPTY;
101 }
102 
103 
104 
105 /*
106  * sorthand sorts a hand of n cards
107  */
108 
109 sorthand( h, n )
110 
111     CARD		h[];
112     int			n;
113 {
114 	register  int		i, j;
115 	CARD			c;
116 
117 	for( i = 0; i < (n - 1); i++ )  {
118 	    for( j = (i + 1); j < n; j++ )  {
119 		if(  ( h[j].rank < h[i].rank )  ||
120 		     ( h[j].rank == h[i].rank && h[j].suit < h[i].suit )  )  {
121 		    c = h[i];
122 		    h[i] = h[j];
123 		    h[j] = c;
124 		}
125 	    }
126 	}
127 }
128 
129