Write a C program that simulates a dice game Prompt the user
Solution
// C++ dice game
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
// roll dice
int roll()
{
int dice = rand()%6 + 1;
return dice;
}
// input valid bet
int validBet(int balance)
{
int bet;
int count = 0;
while(true)
{
cout << \"Enter a valid bet: \";
cin >> bet;
count++;
if(bet <= 0 || bet > balance)
cout << \"Invalid bet\ \";
else
break;
if(count == 3)
{
cout << \"Final balance: $\" << balance << \"\ \";
cout << \"Kindly leave the casino\ \";
return 0;
}
}
return bet;
}
int main()
{
srand(time(0)); // \"Seed\" the random generator
int initialbalance;
int balance;
int bettingAmount;
int dice1;
int dice2;
int sum;
cout << \"\ \ Please Enter your starting balance in whole dollars: \";
cin >> initialbalance;
balance = initialbalance;
cout << \"Your beginning balance is $\" << balance << \", good luck!!\ \ \";
while(true)
{
bettingAmount = validBet(balance);
if (bettingAmount == 0)
{
return 0;
}
dice1 = roll();// Will hold the randomly generated integer between 1 and 6
dice2 = roll(); // Will hold the randomly generated integer between 1 and 6
sum = dice1 + dice2;
if(sum >= 2 && sum <= 6)
{
cout << \"The roll is \" << dice1 << \" and \" << dice2 << \" for a \" << sum << \", you win!\ \";
balance = balance + bettingAmount;
}
else if(sum >= 7 && sum <= 12)
{
cout << \"The roll is \" << dice1 << \" and \" << dice2 << \" for a \" << sum << \", you lose!\ \";
balance = balance - bettingAmount;
}
cout << \"Your balance is $\" << balance << endl;
char choice;
cout << \"\ \ -->Do you want to continue (y/n)? \";
cin >> choice;
if(choice == \'n\' || choice == \'N\')
break;
}
if(balance > initialbalance)
{
cout << \"You have $\" << balance << endl;
cout << \"Well done! Have a wonderful evening!\ \";
}
else
{
cout << \"You have $\" << balance << endl;
cout << \"Better luck next time! Have a wonderful evening!\ \";
}
return 0;
}
/*
output:
Please Enter your starting balance in whole dollars: 100
Your beginning balance is $100, good luck!!
Enter a valid bet: 110
Invalid bet
Enter a valid bet: 50
The roll is 1 and 5 for a 6, you win!
Your balance is $150
-->Do you want to continue (y/n)? y
Enter a valid bet: 110
The roll is 5 and 5 for a 10, you lose!
Your balance is $40
-->Do you want to continue (y/n)? y
Enter a valid bet: 200
Invalid bet
Enter a valid bet: 10
The roll is 3 and 5 for a 8, you lose!
Your balance is $30
-->Do you want to continue (y/n)? n
You have $30
Better luck next time! Have a wonderful evening!
*/


