1. Die.
// Die.h
#ifndef DIE_H
#define DIE_H
class Die {
public:
Die(); // Constructor
void roll(); // Roll the die
int getValue() const; // Get the value of the die
private:
int value; // Value of the die
};
#endif // DIE_H
2. Die.cpp
// Die.cpp
#include "Die.h"
#include <cstdlib> // For rand() and srand()
#include <ctime> // For time()
Die::Die() {
// Initialize random seed
srand(static_cast<unsigned int>(time(0)));
roll(); // Roll the die to get an initial value
void Die::roll() {
value = rand() % 6 + 1; // Random number between 1 and 6
int Die::getValue() const {
return value;
}
3. DieMain.cpp
// DieMain.cpp
#include <iostream>
#include "Die.h"
using namespace std;
void playGame();
int main() {
cout << "Let's play a game of 21!" << endl;
cout << "The winner is the player with the higher total but not over 21." << endl;
cout << "-----------------------------------" << endl;
playGame();
return 0;
void playGame() {
Die userDie, computerDie;
char choice;
int userPoints = 0;
int computerPoints = 0;
do {
// User's turn
cout << "Would you like to roll the dice?" << endl;
cout << "Enter Y for yes or N for no: ";
cin >> choice;
if (choice == 'Y' || choice == 'y') {
userDie.roll();
userPoints += userDie.getValue();
cout << "You have " << userPoints << " points." << endl;
// Computer's turn
if (userPoints <= 21) {
computerDie.roll();
computerPoints += computerDie.getValue();
cout << "Computer has " << computerPoints << " points." << endl;
} while ((choice == 'Y' || choice == 'y') && userPoints <= 21);
cout << "-----------------------------------" << endl;
cout << "The computer had " << computerPoints << " points." << endl;
cout << "You had " << userPoints << " points." << endl;
if (userPoints > 21 && computerPoints > 21) {
cout << "Both players are over 21. No winner!" << endl;
} else if (userPoints > 21) {
cout << "Congratulations! The computer won!" << endl;
} else if (computerPoints > 21) {
cout << "Congratulations! You won!" << endl;
} else if (userPoints > computerPoints) {
cout << "Congratulations! You won!" << endl;
} else if (computerPoints > userPoints) {
cout << "The computer won!" << endl;
} else {
cout << "It's a tie!" << endl;
cout << "Game Over" << endl;