Debian Codegraph @

cards.sh

raw symbols SCIP
1 #!/bin/bash
2 # cards.sh
3
4 # Deals four random hands from a deck of cards.
5
6 UNPICKED=0
7 PICKED=1
8
9 DUPE_CARD=99
10
11 LOWER_LIMIT=0
12 UPPER_LIMIT=51
13 CARDS_IN_SUIT=13
14 CARDS=52
15
16 declare -a Deck
17 declare -a Suits
18 declare -a Cards
19 # It would have been easier to implement and more intuitive
20 #+ with a single, 3-dimensional array.
21 # Perhaps a future version of Bash will support multidimensional arrays.
22
23
24 initialize_Deck ()
25 {
26 i=$LOWER_LIMIT
27 until [ "$i" -gt $UPPER_LIMIT ]
28 do
29 Deck[i]=$UNPICKED # Set each card of "Deck" as unpicked.
30 let "i += 1"
31 done
32 echo
33 }
34
35 initialize_Suits ()
36 {
37 Suits[0]=C #Clubs
38 Suits[1]=D #Diamonds
39 Suits[2]=H #Hearts
40 Suits[3]=S #Spades
41 }
42
43 initialize_Cards ()
44 {
45 Cards=(2 3 4 5 6 7 8 9 10 J Q K A)
46 # Alternate method of initializing an array.
47 }
48
49 pick_a_card ()
50 {
51 card_number=$RANDOM
52 let "card_number %= $CARDS" # Restrict range to 0 - 51, i.e., 52 cards.
53 if [ "${Deck[card_number]}" -eq $UNPICKED ]
54 then
55 Deck[card_number]=$PICKED
56 return $card_number
57 else
58 return $DUPE_CARD
59 fi
60 }
61
62 parse_card ()
63 {
64 number=$1
65 let "suit_number = number / CARDS_IN_SUIT"
66 suit=${Suits[suit_number]}
67 echo -n "$suit-"
68 let "card_no = number % CARDS_IN_SUIT"
69 Card=${Cards[card_no]}
70 printf %-4s $Card
71 # Print cards in neat columns.
72 }
73
74 seed_random () # Seed random number generator.
75 { # What happens if you don't do this?
76 seed=`eval date +%s`
77 let "seed %= 32766"
78 RANDOM=$seed
79 } # Consider other methods of seeding the random number generator.
80
81 deal_cards ()
82 {
83 echo
84
85 cards_picked=0
86 while [ "$cards_picked" -le $UPPER_LIMIT ]
87 do
88 pick_a_card
89 t=$?
90
91 if [ "$t" -ne $DUPE_CARD ]
92 then
93 parse_card $t
94
95 u=$cards_picked+1
96 # Change back to 1-based indexing, temporarily. Why?
97 let "u %= $CARDS_IN_SUIT"
98 if [ "$u" -eq 0 ] # Nested if/then condition test.
99 then
100 echo
101 echo
102 fi # Each hand set apart with a blank line.
103
104 let "cards_picked += 1"
105 fi
106 done
107
108 echo
109
110 return 0
111 }
112
113
114 # Structured programming:
115 # Entire program logic modularized in functions.
116
117 #===============
118 seed_random
119 initialize_Deck
120 initialize_Suits
121 initialize_Cards
122 deal_cards
123 #===============
124
125 exit
126
127
128
129 # Exercise 1:
130 # Add comments to thoroughly document this script.
131
132 # Exercise 2:
133 # Add a routine (function) to print out each hand sorted in suits.
134 # You may add other bells and whistles if you like.
135
136 # Exercise 3:
137 # Simplify and streamline the logic of the script.