Answer to Question #174530 in C++ for Luna

Question #174530

Write a program that plays a dice game with the user. The specification: The user begins with a score of 1000. The user is asked how many points to risk and then the computer rolls two dice. If an even total is rolled, the user loses the points at stake. If an odd total is rolled, the user receives double the points at stake. The program output may look similar to:

(User’s input is underlined)


Sample Run:

You have 1000 points.

Points to risk: 100

Roll is 3 and 5.

You lose.

Play again? Y


You have 900 points.

Points to risk: 200

Roll is 1 and 2.

You win.

Play again? N


Final score: 1300



1
Expert's answer
2021-03-22T22:15:35-0400
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cctype>
using namespace std;

int dice() {
    return rand() % 6 + 1;
}

bool win(int d1, int d2) {
    if ((d1+d2)%2 == 0)
        return true;
    return false;
}

int main() {
    char ans = 'Y';
    int points = 1000;
    srand(time(0));

    while (points > 0 && toupper(ans) == 'Y' ) {
        int risk, d1, d2;
        cout << "You have " << points << " points." << endl;
        cout << "Points to risk: ";
        cin >> risk;
        if (risk > points) {
            cout << "You don have such points" << endl;
            continue;
        }
        d1 = dice();
        d2 = dice();
        cout << "Roll is " << d1 << " and " << d2 << "." << endl;
        if (win(d1, d2) ) {
            cout << "You win." << endl;
            points += risk;
        }
        else {
            cout << "You lose." << endl;
            points -= risk;
        }
        cout << "Play again? ";
        cin >> ans;
        cout << endl;
    }
    cout << "Final score: " << points << endl;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS