So now that we’ve programmed our “Card” class, let’s think further about what other real-life objects within BlackJack could be mapped into programmatic ones. The “Card” class was a fairly obvious one and hopefully it has served as a clue to the next class we need, the “Deck“…
It may not be a single object in a “real-life” sense but you can hopefully see that a deck represents a single entity in the game of blackjack. Once you start to imagine what a deck contains and what you can do with a deck, it will probably stand out as an object more clearly:
So what fields or pieces of information are required for a deck, think logically about what makes up a deck and hopefully you will come up with a similar list to this:
- An array of cards: This one’s pretty obvious, you can’t have a deck without cards, and even though our new “Card” class isn’t a regular data type, we can still make an array of them.
- Number of cards in the deck: Again, this seems like a reasonable field. It could probably be worked out from the array but if we’re building an adaptable class then this variable allows us to change the size of the deck more easily.
- Top card: This one may not initially seem obvious but if you imagine the deck as an array of cards, you can probably also imagine we need to know where we’re up to in that array as we deal cards out.
And there you have the fields needed in our “Deck” class!
So what can you do with a deck of cards? Well again, thinking logically, you should be able to come up with a list much like mine:
- Select a random card from the deck: Many card games require the ability to find a random card in the deck and so we’ll create a method that can do that.
- Shuffle the deck: A pretty obvious one really, you can’t go playing BlackJack or any card game for that matter with a perfectly ordered set of cards.
- Deal a card from the deck: Again, pretty obvious. I need to have the ability to grab a card from the deck and give it to someone.
And so without any code whatsoever we’ve come up with the skeleton of our “Deck” class. Using yUML again here’s a visual representation of this new class:
Okay, so the planning is done, let’s go and make this bad boy!