13.9. Shuffling and dealing

In Section 13.6, I wrote pseudocode for a shuffling algorithm. Assuming that we have a function called shuffleDeck that takes a deck as an argument and shuffles it, we can create and shuffle a deck:

Deck deck;               // create a standard 52-card deck
deck.shuffleDeck ();     // shuffle it

Then, to deal out several hands, we can use subdeck:

Deck hand1 = deck.subdeck (0, 4);
Deck hand2 = deck.subdeck (5, 9);
Deck pack = deck.subdeck (10, 51);

This code puts the first 5 cards in one hand, the next 5 cards in the other, and the rest into the pack.

When you thought about dealing, did you think we should give out one card at a time to each player in the round-robin style that is common in real card games? I thought about it, but then realized that it is unnecessary for a computer program. The round-robin convention is intended to mitigate imperfect shuffling and make it more difficult for the dealer to cheat. Neither of these is an issue for a computer.

This example is a useful reminder of one of the dangers of engineering metaphors: sometimes we impose restrictions on computers that are unnecessary, or expect capabilities that are lacking, because we unthinkingly extend a metaphor past its breaking point. Beware of misleading analogies.

The active code below deals a deck of cards among three players for a game of Go Fish. Feel free to experiment with the code and deal decks for other games like War, Poker, and Egyptian Ratscrew.

Before you keep reading...

Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.

You have attempted 1 of 2 activities on this page