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