4

我刚刚完成了一个扫雷类型游戏的编码,一切都很好,除了每次我运行应用程序时,它都会生成相同的数字(我运行了 3 次不同的时间,将输出保存到 3 个文本文件并diff在 Linux 中使用了命令,它没有发现任何差异)。它是播种的,time(NULL)所以它应该每次都改变,对吧?

这是我的代码:

主文件

#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;
}
4

3 回答 3

9

它是按时间播种的(NULL)

如果是的话,我看不到。事实上,在您的代码中搜索它不会返回任何内容。如果您没有显式播种,则默认行为与您使用值 1 播种时相同。

您需要明确声明如下内容:

srand (time (NULL));

main某个地方的开始(并确保你只做一次)。

尽管请记住,这使其依赖于当前时间 - 如果您在同一秒内启动多个作业(或无论您的时间分辨率是什么),它们将以相同的种子开始。

来自 C 标准(这些兼容性功能基于 C++):

srand 函数将该参数用作新伪随机数序列的种子,这些伪随机数将由后续调用 rand 返回。如果随后使用相同的种子值调用 srand,则应重复伪随机数序列。如果在对 srand 进行任何调用之前调用了 rand,则应生成与第一次调用 srand 时相同的序列,种子值为 1。

于 2011-09-29T03:32:18.880 回答
1

您需要播种随机发生器。一开始就打电话srand()

于 2011-09-29T03:32:41.877 回答
1

要添加其他人的答案,您可以使用 Mersenne Twister 算法,它是 C++11 库的一部分。它迅速成为许多常见软件中生成随机数的标准。

例如,这是我编写的函数,我经常在其他代码中使用它来生成随机数:

 std::vector<double> mersennetwister(const int& My,const int& Mz,
 const int& Ny,const int& Nz)
 {
 int ysize = (My + 2*Ny + 1);
 int zsize = (Mz + 2*Nz + 1);
 int matsize = ysize*zsize;
 unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
 // Seeding the generator with the system time
 std::mt19937_64 generator (seed);
 // Calling the Mersenne-Twister Generator in C++11
 std::uniform_real_distribution<double> distribution(0,1);
 // Specifying the type of distribution you want
 std::vector<double>  randarray(matsize,0);
 // Saving random numbers to an array
 for (int i=0;i<matsize;++i)
 {
    randarray[i] = distribution(generator); // Generates random numbers fitting the 
    // Distribution specified earlier
 }
 return(randarray);
 } 

底线:C++11 在数值运算方面有一些出色的特性,研究它们是个好主意。至于 Mersenne Twister,http ://en.wikipedia.org/wiki/Mersenne_twister

于 2013-06-05T01:11:47.433 回答