This question already has answers here:
Recommended way to initialize srand?
(15个答案)
5年前关闭。
我试图在C ++中实现掷骰子游戏,规则如下。因此,我创建了一个函数,该函数将为我生成两个数字,有时该函数需要调用两次,但是第二次调用该函数时,它会给我相同的随机数,这是第一次给我的。
我想随机化第二次调用
示例输出1:
玩家掷出3 + 4 = 7
玩家赢了!
示例输出2:
玩家掷出2 + 2 = 4
点是4
玩家掷出2 + 2 = 4
玩家赢了!
示例输出3:
玩家掷出1 + 5 = 6
点是6
玩家掷出1 + 5 = 6
玩家赢了!
游戏规则:
规则:玩家投掷两个6个面子骰子,如果它们的总和是7或11,则获胜。
如果总和是2,3或12,它们就会松散。
如果它是4,5,6,8,9,10,12,则成为“点”,玩家必须再次掷骰。
然后,玩家不断滚动直到再次击中“点”,然后获胜
如果他命中7,就会松懈。
码:
这会将随机数生成器的种子重置为当前时间。程序启动时,仅执行一次。如果您在同一秒内执行两次(以使
(15个答案)
5年前关闭。
我试图在C ++中实现掷骰子游戏,规则如下。因此,我创建了一个函数,该函数将为我生成两个数字,有时该函数需要调用两次,但是第二次调用该函数时,它会给我相同的随机数,这是第一次给我的。
我想随机化第二次调用
rollDice()
函数时得到的数字。我怎么做?示例输出1:
玩家掷出3 + 4 = 7
玩家赢了!
示例输出2:
玩家掷出2 + 2 = 4
点是4
玩家掷出2 + 2 = 4
玩家赢了!
示例输出3:
玩家掷出1 + 5 = 6
点是6
玩家掷出1 + 5 = 6
玩家赢了!
游戏规则:
规则:玩家投掷两个6个面子骰子,如果它们的总和是7或11,则获胜。
如果总和是2,3或12,它们就会松散。
如果它是4,5,6,8,9,10,12,则成为“点”,玩家必须再次掷骰。
然后,玩家不断滚动直到再次击中“点”,然后获胜
如果他命中7,就会松懈。
码:
#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!";
}
最佳答案
srand(time(0));
这会将随机数生成器的种子重置为当前时间。程序启动时,仅执行一次。如果您在同一秒内执行两次(以使
time
返回相同的值),则每次都会获得相同的随机数序列。