我刚刚完成扫雷类型游戏的编码,一切都很好,除了每次运行该应用程序时,它都会生成相同的数字(我运行了 3 次不同的时间,将输出保存到 3 个文本文件并使用diff
Linux 中的命令,没有发现任何差异)。它的种子是time(NULL)
所以每次都应该改变,对吗?
这是我的代码:
main.cpp
#include <iostream>
#include <cstdlib>
#include <time.h>
#include <string>
#include "Minesweeper/box.h"
#include <cstdio>
int main(int argc, char** argv){
using namespace std;
bool gameOver = false;
int x, y, score = 0;
const int HEIGHT = 10;
const int WIDTH = 10;
unsigned int Time = time(0);
cout << "Welcome to Minesweeper. " << endl;
//setup grid
Box grid[10][10];
for(int i = 0; i < WIDTH; i++)
for(int n = 0; n < HEIGHT; n++){
unsigned int value = rand() %100 + 1;
cout << value << endl;
if(value <= 38){
grid[i][n].setFill(MINE);
//cout << i << "," << n << " is mined." << endl;
}
else
grid[i][n].setFill(EMPTY);
}
for(int r = 0; r < WIDTH; r++)
for(int l = 0; l < HEIGHT; l++)
if(grid[r][l].getFill() == EMPTY)
cout << r << "," << l << " - EMPTY." << endl;
else if (grid[r][l].getFill() == MINE)
cout << r << "," << l << " - MINE." << endl;
while(!gameOver){
cout << "Enter coordinates (x,y): ";
scanf("%i,%i",&x,&y);
if(grid[x][y].getFill() == MINE)
gameOver = true;
else{
cout << "Good job! (You chose " << x << "," << y << ")" << endl;
score++;
}
}
cout << "You hit a mine! Game over!" << endl;
cout << "Final score: " << score << endl;
getchar();
return EXIT_SUCCESS;
}
它是按时间播种的(NULL)
如果是的话我就看不到了事实上,在代码中搜索它不会返回任何结果。如果您没有显式设定种子,则默认行为与使用值 1 设定种子相同。
您需要明确说明如下内容:
srand (time (NULL));
开始时main
某处(并确保你这样做once并且仅一次)。
尽管请记住,这使其取决于当前时间 - 如果您在同一秒内启动多个作业(或无论您的时间分辨率是什么),它们将以相同的种子开始。
来自 C 标准(C++ 的这些兼容性功能基于该标准):
srand 函数使用参数作为后续调用 rand 返回的新伪随机数序列的种子。如果随后使用相同的种子值调用 srand,则应重复伪随机数序列。如果在对 srand 进行任何调用之前调用 rand,则应生成与首次使用种子值 1 调用 srand 时相同的序列。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)