14. Finishing the “Deck”

So we’ve constructed the values of our fields in the deck, we’ve created a method that can find a random card for us and we just have two methods left…

The “shuffle” method
This method mainly involves some logical thinking, if you want to shuffle the contents of an array then all you have to do is pick two random positions and swap their contents…if you do this a bunch of times then the deck is shuffled:

int i, j, k;
Card temp;
for (i = 0; i < 1000; i++) {
   j = randomCard();
   k = randomCard();
   temp = cards[j];
   cards[j] = cards[k];
   cards[k] = temp;

While this method may not mimic the actual way a deck is shuffled in a casino, it ensures a well-shuffled deck for use in the game. There are a couple of things to note about it though:

  1. randomCard(): Notice I’ve called my “randomCard” method without using the period? This is because I am within the class where that method resides. When I’m inside a class I’m basically programming procedurally and any methods I’ve created can be referenced directly.
  2. private methods: Because “randomCard” has been declared as private, it can only be used inside it’s containing class. If you felt a need to let users of this class have access to that method then you could change the implementation but in this project I’ve decided to keep it private.
  3. Temporary objects: I’ve made a temporary Card object to help me in the swap…objects can usually be treated just like any of the regular data types you’re used to, they certainly offer much more than that but they still maintain most of the traits you would expect of a data type.

The “deal” method
And lastly we need to create a method that allows us to deal a card from our deck, this one is pretty simple really:

return cards[topCard + 1];

This is far from a beautiful implementation, it doesn’t account for someone trying to deal too many cards from the deck and the logic of decreasing our variable before using it is all out of whack but I’ll leave the job of tidying this project to you :-)

And that’s it! Now we have a functional and fairly elegant “Deck” class we can use in this project.

So with the playing cards all sorted, what other objects exist in the game of Blackjack. Well what about the hand that each player and dealer have?

Leave a Comment

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>