I am trying to implement the craps game in C++, rules are given below. So I created a function which will generate two numbers for me, sometime this function needs to be called twice, but when it is called for the second time its giving me the same random number it gave me the first time.
I want to randomize the numbers I get in the the second call to rollDice()
function. How do I do that?
Example output 1:
Player rolled 3 + 4 = 7
Player won!
Example output 2:
Player rolled 2 + 2 = 4
Point is 4
Player rolled 2 + 2 = 4
Player won!
Example output 3:
Player rolled 1 + 5 = 6
Point is 6
Player rolled 1 + 5 = 6
Player won!
Game rules: Rule: A player throws two 6 face dice, if their sum is 7 or 11, they Win. if the sum is 2,3 or 12 they loose. if it's 4,5,6,8,9,10,12 it becomes a "point" and the player has to roll again. The player then keeps rolling until he hit the "point" again and he wins and loose if he hits a 7.
Code:
#include<iostream>
#include<ctime>
#include <cstdlib>
using namespace std;
//Generating two rand numbers from 1 to 6
int rollDice()
{
srand(time(0));
int face1 = 1 + rand()%6;
int face2 = 1 + rand()%6;
int sum = face1 + face2;
cout << "Player rolled " << face1 << " + " << face2 << " = " << sum << endl;
return sum;
}
string gameStatus; //Hold status of game; WIN, CONTINUE, LOST
int sumOfDice = rollDice();
int point = 0; //This will hold sum of dice if it's default case defined below in Switch.
int main()
{
switch(sumOfDice)
{
case 7:
case 11:
gameStatus = "WIN";
break;
case 2:
case 3:
case 12:
gameStatus = "LOST";
break;
default:
gameStatus = "CONTINUE";
point = sumOfDice;
cout << "Point is " << point << endl;
}
while (gameStatus == "CONTINUE")
{
int rollAgain = rollDice();
if (rollAgain == point)
gameStatus = "WIN";
else if (rollAgain == 7)
gameStatus = "LOST";
}
if (gameStatus == "WIN")
cout << "Player won!";
if (gameStatus == "LOST")
cout << "Player lost!";
}