I am currently working on a dice game. Where The user rolls a pair of dice first, so lets say he rolled and Dice 1 = 2 and Dice 2 = 3. So the total is 5 now. Now, he needs to get 5 (total) again in order to win, if he didnt get 5 in his next move then he rolls again and the game continues. But he looses if at any point of time, he rolled a total of two.
So,please tell me how do I store value of the first roll and compare it with the next move(s). I tried something, but it does not seem to work.
#include<iostream>
#include<ctime> // for the time() function
#include<cstdlib> // for the srand() and rand() functions
using namespace std;
// Declare variables
//int compInput;
int userInput;
int die1 = 0;
int die2 = 0;
int dieTotal = 0;
int Dice ()
{
// roll the first die
die1 = (rand() % 6 ) + 1;
// roll the second die
die2 = (rand() % 6 ) + 1;
}
// iniating a second two pair dice function.
int compDice()
{
Dice();
dieTotal = die1 + die2;
return (dieTotal);
}
// User Rolling the dice and calucalting the total here
int userGame()
{
cout << "\nUser turn --- Press 2 to roll" << endl;
cin >> userInput;
if ( userInput == 2 )
{
Dice ();
cout << "\nThe user rolled Dice 1 = " << die1 << " and Dice 2 = " << die2 << endl;
cout << "Total = " << die1 + die2 << endl;
}
else {
cout << "Wrong input.";
//userGame();
}
return (die1 + die2 );
}
int checkForWin ()
{
while (true)
{
int result1 = compDice();
int result = userGame();
// int finalResult = dieTotal;
if (result == result1 )
{
cout << "\nUser won. Computer looses....m " << endl;
break;
}
else if (result == 2)
{
cout << "\nUser looses. Computer won." <<endl;
break;
}
else
{
}
}
}
// Calling for the checkForWin() function in main and the srand.
int main ()
{
cout << "This is the Dice game. " << endl;
// set the seed
srand(time(0));
checkForWin(); // Initiating the game.
return 0;
}
After our comment chat/misunderstandings, I’ve taken the liberty of copying your code and modifying it (as little as possible to maintain your coding style – I would not recommend this style for any future projects) to produce the results you want. Let me know if it works (simple testing showed it worked, may have missed some other quirks)