6.8.1. Exercises: Managed Containers, Composites and Aggregates

[ fromfile: inheritance-intro.xml id: x-datastructures ]

Playing cards have been in existence in various forms for more than 600 years. They are used for a large number of games of chance and are a favorite subject for exercises in math, statistics, and computer science.

In Europe, and the West, there is a standard card set, called a deck, which is familiar to most people. It consists of 52 cards, divided into 4 subsets, called suits . Each suit consists of 13 cards designated by the names: A (Ace), 2, 3, 4, 5, 6, 7, 8, 9, T (Ten), J (Jack), Q (Queen), K (King). Many card games begin by supplying each player with a small set of cards (randomly extracted from the deck) called a hand.

In this exercise you design data types to represent a deck and a hand of cards. Later you will revisit these clases to elaborate the rules and add graphics. Figure 6.5 suggests one way of representing these classes.

Figure 6.5.  Card Game UML

Card Game UML

Following are some hints:

Example 6.29. src/cardgame/datastructure/cardgame-client.cpp

[ . . . . ]
#include "carddeck.h"
#include <QTextStream>
#include <QtGui>
int main(int argc, char* argv[]) {
    QApplication app(argc, argv);
    QTextStream cout(stdout);    
    CardDeck deck;
    CardHand hand;
    int handSize, playerScore, progScore;
    cout << "How many cards in a hand? " << flush;
    handSize = QInputDialog::getInt(0, QString("getInt()"), 
        QString("How many cards in hand?"), 1, 5);
    QMessageBox::StandardButton sb;
    do {
        hand = deck.deal(handSize);
        cout << "Here is your hand:" << endl;
        cout << hand.toString() << endl;
        playerScore = hand.getValue();
        cout << QString("Your score is: %1 points.")
                         .arg(playerScore) << endl;
        // Now a hand for the dealer:
        hand = deck.deal(handSize);
        progScore = hand.getValue();
        cout << "Here is my hand:" << endl;
        cout << hand.toString() << endl;
        cout << QString("My score is: %1 points.")
                         .arg(progScore) << endl;
        cout << QString("%1 win!!")
              .arg((playerScore > progScore)?"You":"I") << endl;
        sb = QMessageBox::question(0, QString("QMessageBox::question()"),
            QString("Another hand?"), QMessageBox::Yes | QMessageBox::No);
            
    } while (sb == QMessageBox::Yes);
}