In this sample chapter, author Clayton Walnum teaches you how to create a class for manipulating a deck of cards. Learn how to write a class to represent a single card or a deck of cards, and how to use classes to write card programs such as blackjack.

This chapter was selected from Sams Teach Yourself Game Programming with Visual Basic in 21 Days.

Few types of games are more popular than card games. Most households have a
deck of cards, and probably more fortunes are won and lost over a card table
than on a roulette wheel or a slot machine. That popularity crosses over to
computer card games as well. The bottom line is that if you're going to be
a Visual Basic game programmer, you need to know how to use VB to handle a deck
of virtual cards.

Fortunately, Lady Luck is smiling upon you. In this chapter, not only will
you create a class for manipulating a deck of cards, but you'll also get a
full set of graphical images for your cards. If there's one thing that
discourages most programmers from creating card games, it's the daunting
challenge of drawing images for 52 cardsespecially the face cards, which
are the most graphically complex cards in the deck.

Specifically, today you'll learn the following:

How to write a class to represent a single card

How to write a class to represent a deck of cards

How to write card programs using classes

How to write a simple blackjack game

Deck-Handling Functions

In the following sections, you'll create a class that you can use to
program card games. Before creating a class, however, you have to consider
carefully the different ways that you must manipulate the data encapsulated in
the class. After you've analyzed your game's needs, you can then write
the class's functions. Unfortunately for programmers, there are more card
games than craters on the moon. This makes creating a complete card class a
nearly impossible task. You can never predict all the different ways that you
might need to manipulate cards in your programs.

Therefore, the best you can do is to write the functions that every card game
needssuch as shuffling a deck and dealing handsand then add more
specific functions as you need them. That's the approach this chapter will
take with the clsCard class, which will be used in the next few
chapters. After you understand how the clsCard class works, you'll
be able to add any other functions that you need to create specific card
games.