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
#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;
}
Comments
Leave a comment