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