Home > Articles > Programming > Visual Basic

The clsDeck Class

Although Table 8.1 explains how the clsCard class works, you probably won't often need to access the clsCard class directly because it's handled mostly by the clsDeck class. The source code looks like Listing 8.2.

Listing 8.2 The clsDeck Class

1: '///////////////////////////////////////////////////////////
2: '// The clsDeck class
3: '///////////////////////////////////////////////////////////
4: 
5: Option Explicit
6: 
7: Private m_Hands(MAXHANDS) As hand
8: Private m_Cards(51) As clsCard
9: Private m_PositionInDeck As Integer
10: Private m_NumCardsInHand As Integer
11: 
12: '///////////////////////////////////////////////////////////
13: '// Class_Initialize
14: '///////////////////////////////////////////////////////////
15: Private Sub Class_Initialize()
16:  Dim i As Integer
17: 
18:  Randomize
19:  m_PositionInDeck = 0
20:  For i = 0 To 51
21:   Set m_Cards(i) = New clsCard
22:   m_Cards(i).value = i
23:  Next i
24:  Init_Hands
25: End Sub
26: 
27: '///////////////////////////////////////////////////////////
28: '// Shuffle
29: '//
30: '// This subroutine shuffles the deck, resets the
31: '// m_PositionInDeck marker, and initializes the m_Hands.
32: '///////////////////////////////////////////////////////////
33: Sub Shuffle()
34:  Dim CardNum As Integer
35:  Dim temp As clsCard
36:  Dim i As Integer
37: 
38:  m_PositionInDeck = 0
39:  For i = 0 To 51
40:   CardNum = Int(Rnd * 52)
41:   Set temp = m_Cards(i)
42:   Set m_Cards(i) = m_Cards(CardNum)
43:   Set m_Cards(CardNum) = temp
44:  Next i
45:  Init_Hands
46: End Sub
47: 
48: '///////////////////////////////////////////////////////////
49: '// Deal
50: '//
51: '// This subroutine deals num cards into the given hand,
52: '// displaying the cards on screen starting at x,y and
53: '// spacing them each one card width over plus the spacing
54: '// parameter. The parameter face controls whether the cards
55: '// are dealt face-up or face-down.
56: '///////////////////////////////////////////////////////////
57: Sub Deal(num As Integer, hand As Integer, x As Integer, _
58:   y As Integer, spacing As Integer, face As Integer)
59:  Dim pos As Integer
60:  Dim i As Integer
61: 
62:  For i = 0 To num - 1
63:   pos = m_Hands(hand).PositionInHand
64:   Set m_Hands(hand).cards(pos) = m_Cards(m_PositionInDeck)
65:   m_Cards(m_PositionInDeck).Display x, y, face
66:   m_PositionInDeck = m_PositionInDeck + 1
67:   If m_PositionInDeck > 51 Then m_PositionInDeck = 0
68:   m_Hands(hand).PositionInHand = _
69:     m_Hands(hand).PositionInHand + 1
70:   If m_Hands(hand).PositionInHand > 51 Then _
71:     m_Hands(hand).PositionInHand = 0
72:   x = x + 56 + spacing
73:  Next i
74: End Sub
75: 
76: '///////////////////////////////////////////////////////////
77: '// ShowHand
78: '//
79: '// This subroutine shows all the cards in the given hand
80: '// starting at the screen coordinates x,y and spaced
81: '// apart according to the spacing parameter. The cards
82: '// are displayed face-up or face-down depending on the
83: '// face parameter.
84: '///////////////////////////////////////////////////////////
85: Sub ShowHand(hand As Integer, x As Integer, y As Integer, _
86:   spacing As Integer, face As Integer)
87:  Dim num As Integer
88:  Dim i As Integer
89: 
90:  num = m_Hands(hand).PositionInHand
91:  For i = 0 To num - 1
92:   m_Hands(hand).cards(i).Display x, y, face
93:   x = x + 56 + spacing
94:  Next i
95: End Sub
96: 
97: '///////////////////////////////////////////////////////////
98: '// DealReplace
99: '//
100: '// This subroutine deals one card into the given hand,
101: '// replacing the card at the position pos. The parameter
102: '// face controls whether the card is displayed face-up
103: '// or face-down.
104: '///////////////////////////////////////////////////////////
105: Sub DealReplace(hand As Integer, pos As Integer, _
106:   face As Integer)
107:  Dim x As Integer
108:  Dim y As Integer
109: 
110:  x = m_Hands(hand).cards(pos).xPosition
111:  y = m_Hands(hand).cards(pos).yPosition
112:  Set m_Hands(hand).cards(pos) = m_Cards(m_PositionInDeck)
113:  m_Cards(m_PositionInDeck).Display x, y, face
114:  m_PositionInDeck = m_PositionInDeck + 1
115:  If m_PositionInDeck > 51 Then m_PositionInDeck = 0
116: End Sub
117: 
118: '///////////////////////////////////////////////////////////
119: '// Discard
120: '//
121: '// This subroutine removes the card at position pos from
122: '// the hand specified bt the hand parameter.
123: '///////////////////////////////////////////////////////////
124: Sub Discard(hand As Integer, pos As Integer)
125:  Dim x As Integer
126:  Dim y As Integer
127:  Dim DiscardPos As Integer
128:  Dim i As Integer
129: 
130:  DiscardPos = m_Hands(MAXHANDS - 1).PositionInHand
131:  m_Hands(MAXHANDS - 1).PositionInHand = _
132:    m_Hands(MAXHANDS - 1).PositionInHand + 1
133:  Set m_Hands(MAXHANDS - 1).cards(DiscardPos) = _
134:    m_Hands(hand).cards(pos)
135:  For i = pos To m_Hands(hand).PositionInHand - 1
136:   Set m_Hands(hand).cards(i) = m_Hands(hand).cards(i + 1)
137:  Next i
138:  m_Hands(hand).PositionInHand = m_Hands(hand).PositionInHand - 1
139: End Sub
140: 
141: '///////////////////////////////////////////////////////////
142: '// EraseCard
143: '//
144: '// This subroutine erases the card at position pos in
145: '// the hand specified by the hand parameter.
146: '///////////////////////////////////////////////////////////
147: Sub EraseCard(HandNum As Integer, pos As Integer)
148:  m_Hands(HandNum).cards(pos).EraseCard
149: End Sub
150: 
151: '///////////////////////////////////////////////////////////
152: '// ShowHandCard
153: '//
154: '// This subroutine displays the card at position pos in
155: '// the given hand. The parameter face controls whether
156: '// the card is displayed face-up or face-down.
157: '///////////////////////////////////////////////////////////
158: Sub ShowHandCard(hand As Integer, pos As Integer, _
159:   face As Integer)
160:  If face = FaceUp Then
161:   m_Hands(hand).cards(pos).ShowFace
162:  Else
163:   m_Hands(hand).cards(pos).ShowBack
164:  End If
165: End Sub
166: 
167: '///////////////////////////////////////////////////////////
168: '// MoveHandCard
169: '//
170: '// This subroutine moves the card at position pos in the
171: '// given hand to new screen coordinates. The parameter
172: '// face controls whether the card is displayed face-up or
173: '// face-down.
174: '///////////////////////////////////////////////////////////
175: Sub MoveHandCard(hand As Integer, pos As Integer, _
176:   x As Integer, y As Integer, face As Integer)
177:  m_Hands(hand).cards(pos).Display x, y, face
178: End Sub
179: 
180: '///////////////////////////////////////////////////////////
181: '// GetCardValue
182: '//
183: '// This function returns the value of the card at pos in
184: '// the given hand. The value is a number from 0 to 51.
185: '///////////////////////////////////////////////////////////
186: Function GetCardValue(hand As Integer, _
187:   pos As Integer) As Integer
188:  GetCardValue = m_Hands(hand).cards(pos).value
189: End Function
190: 
191: '///////////////////////////////////////////////////////////
192: '// Init_Hands
193: '//
194: '// This subroutine initializes the m_Hands property,
195: '// setting all cards in m_Hands to Nothing and setting
196: '// each hand's PositionInHand property to zero.
197: '///////////////////////////////////////////////////////////
198: Sub Init_Hands()
199:  Dim i As Integer
200:  Dim j As Integer
201: 
202:  For i = 0 To MAXHANDS - 1
203:   m_Hands(i).PositionInHand = 0
204:   For j = 0 To 51
205:    Set m_Hands(i).cards(j) = Nothing
206:   Next j
207:  Next i
208: End Sub
209: 
210: '///////////////////////////////////////////////////////////
211: '// Restore
212: '//
213: '// This subroutine sets the position in the deck back to
214: '// the beginning of the deck.
215: '///////////////////////////////////////////////////////////
216: Sub Restore()
217:  m_PositionInDeck = 0
218: End Sub
219: 
220: '///////////////////////////////////////////////////////////
221: '// Get NumCardsInHand
222: '///////////////////////////////////////////////////////////
223: Property Get NumCardsInHand(hand As Integer) As Integer
224:  If hand < 0 Or hand > MAXHANDS - 1 Then Err.Raise 9
225:  NumCardsInHand = m_Hands(hand).PositionInHand
226: End Property

Analysis - In the class's Class_Initialize method, Line 18 ensures that the class is capable of producing a different shuffled deck every time it's used. Line 19 initializes the m_PositionInDeck property, and Lines 20 through 23 create 52 objects of the clsCard class. The Init_Hands call (Line 24) empties all the card hands.

Analysis - The Shuffle method shuffles the deck (Lines 39 to 44) by swapping each card with another randomly selected card. The method also resets the m_PositionInDeck marker (Line 38) to 0, which makes the first card in the deck the next card to be drawn. Finally, the method empties all hands (Line 45).

ANALYSIS - The Deal method deals the requested number of cards (specified by the num parameter) into the hand specified by the hand parameter. The cards are displayed on the screen starting at x,y, with each card spaced one card width over plus the spacing parameter. The parameter face controls whether the cards are dealt face-up or face-down. Line 62 begins a For statement that iterates once for each card to display. Inside the For loop, Line 63 gets the position in the hand to which the current card should be dealt, and Line 64 sets the card in that hand position to the next card in the deck. Line 65 calls the card object's Display method to paint the card on the screen, and Lines 66 and 67 move the current position in the deck to the next card. Lines 68 to 71 move forward the location for the next card in the hand. Finally, Line 72 adds the spacing parameter to the horizontal position for the next card to display.

Analysis - This ShowHand method shows all the cards in the given hand, starting at the screen coordinates x,y and spaced apart according to the spacing parameter. The cards are displayed face-up or face-down depending on the face parameter. Line 90 gets the number of cards in the hand, and Lines 91 to 94 call each card object's Display method to show the card on the screen. Notice how the Display method is a member of the currently indexed element of the cards() array, which is itself a member of the m_Hands() array.

Analysis - The DealReplace method deals one card into the given hand, replacing the card at the position pos. The parameter face controls whether the card is displayed face-up or face-down. Lines 110 and 111 get the coordinates of the card to replace, and Line 112 places the next card in the deck into the given position in the hand. Line 113 then displays the new card on the screen. Finally, Lines 114 and 115 move the position in the deck to the next card.

Analysis - The Discard method removes the card at position pos from the hand specified by the hand parameter. Line 130 gets the current position in the discard hand, and Lines 131 and 132 move the discard hand's current position forward one card. Line 133 removes the discarded card from the hand and places it into the discard hand, and then Lines 135 to 137 move the cards in the hand back one position in order to fill in the position where the discarded card used to be. Finally, Line 138 updates the position in the hand, setting it back one.

Analysis - The EraseCard method erases the card at position pos in the hand specified by the hand parameter. Calling the card object's EraseCard method is all that's required to erase the card from the screen.

Analysis - The ShowHandCard method displays the card at position pos in the given hand. The parameter face controls whether the card is displayed face-up or face-down. Lines 160 and 161 display the card's face if the face parameter is FaceUp, and Lines 162 and 163 display the card face-down if the face parameter is FaceDown.

Analysis - The MoveHandCard method moves the card at position pos in the given hand to new screen coordinates. The parameter face controls whether the card is displayed face-up or face-down. Line 177 calls the card object's Display method to display the card in its new position.

Analysis - The GetCardValue function returns the value of the card at pos in the given hand. The value is a number from 0 to 51 and is obtained from the card object's value property in Line 188.

Analysis - The Init_Hands method initializes the m_Hands property, setting all cards in m_Hands to Nothing (Lines 204 to 206) and setting each hand's PositionInHand property to zero (Line 203).

Analysis - The Restore method sets the position in the deck back to the beginning of the deck. It does this in Line 217 by setting m_PositionInDeck to 0. This method is handy when you want to reuse the same deck of cards.

In the clsDeck class, the variable m_Cards is a 52-element array of clsCard objects. These objects make up the deck of cards. The integer m_PositionInDeck keeps track of the next card to be dealt. That is, at the beginning of a program, m_PositionInDeck is 0, indicating that the first card in the deck will be dealt next. Each time a card is dealt, m_PositionInDeck increments. When m_PositionInDeck equals 51, there's only one card left to deal in the deck. To avoid array-indexing errors, if your program tries to deal more than 52 cards before reshuffling the deck, m_PositionInDeck starts back at 0 and goes through the deck again.

The variable m_Hands is an array of hand objects, which is a user-defined data type (defined in a module called Cards.bas). The hand data type is as follows:

Public Type hand
 PositionInHand As Integer
 cards(51) As clsCard
End Type

As you can see, the members of hand are similar to two members of the clsDeck class. The integer PositionInHand keeps track of the position in the hand where the next card will be dealt. The array cards holds the clsCard objects that make up the hand.

Although you cannot anticipate all the different ways that you might need to manipulate a deck of cards, the clsDeck class includes 10 methods that you can call in your programs. These methods, which are listed in Table 8.2, enable you to program many card games without adding anything to the class. Study this table now so that you understand how to use the clsDeck class.

Table 8.2 Methods of the clsDeck Class

Member Function

Description

Shuffle

Shuffles the deck and resets the m_PositionInDeck marker. It also calls the private member function Init_Hands to initialize all eight hands that the clsDeck class handles.

Deal(num As Integer,

Deals num cards into the hand specified by the hand parameter and hand As Integer, x As displays the cards onscreen, starting at the coordinates x and y and Integer, y As Integer, spacing the cards each one card-width over plus the spacing para-spacing As Integer, meter. The parameter face must have the value FaceUp or FaceDown,face As Integer) which controls whether the cards are dealt face-up or face-down.

ShowHand(hand As

Shows all the cards in the hand specified by hand, starting at the Integer, x As Integer, screen coordinates x and y and spaced apart according to the spacingy As Integer, spacing parameter. The cards are displayed face-up or face-down depending As Integer, face As on the face parameter with a value that must be either FaceUp or Integer) FaceDown.

DealReplace(hand As

Deals one card into the given hand, replacing the card at the position Integer, pos As pos. The parameter face, which must be the value FaceUp or FaceDown Integer, face As controls whether the cards are displayed face-up or face-down.Integer)

EraseCard(HandNum As

Erases the card at position pos in the hand specified by the HandNum Integer, pos As parameter.Integer)

Discard(hand As

Removes the card at position pos from hands(hand), placing the card Integer, pos As into hands(7), which is the discard pile.Integer)

Sub ShowHandCard(hand

Displays the card at position pos in the given hand. The parameter As Integer, pos As face, which must have the value FaceUp or FaceDown, controls Integer, face As whether the cards are displayed face-up or face-down.Integer)

MoveHandCard(hand As

Moves the card at position pos in the given hand to the new screenInteger, pos As coordinates, x and y. The parameter face, which must have the value Integer, x As Integer, FaceUp or FaceDown, controls whether the card is displayed face-up y As Integer, face As or face-down.Integer)

GetCardValue(hand As

Returns the value of the card at the position pos in the given hand. Integer, pos As The value is a number from 0 to 51.Integer)

Restore

Sets the m_PositionInDeck data member back to 0, restoring the deck to the state it was in before the program dealt the first card.


InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020