xref: /original-bsd/games/cribbage/cards.c (revision bf6f0c4a)
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:
107  *	Sort a hand of n cards
108  */
109 sorthand(h, n)
110 register CARD		h[];
111 int			n;
112 {
113 	register CARD		*cp, *endp;
114 	CARD			c;
115 
116 	for (endp = &h[n]; h < endp - 1; h++)
117 	    for (cp = h + 1; cp < endp; cp++)
118 		if ((cp->rank < h->rank) ||
119 		     (cp->rank == h->rank && cp->suit < h->suit)) {
120 		    c = *h;
121 		    *h = *cp;
122 		    *cp = c;
123 		}
124 }
125 
126