air*_*n19 4 c++ random minesweeper
我刚刚完成了Minesweeper类型游戏的编码,除了每次运行应用程序之外一切都很好,它生成相同的数字(我运行了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;
}
Run Code Online (Sandbox Code Playgroud)
按时间播种(NULL)
如果是的话,我看不到它.实际上,在代码中搜索它不会返回任何内容.如果您没有显式种子,则默认行为与您使用值1播种时的默认行为相同.
您需要明确说明以下内容:
srand (time (NULL));
Run Code Online (Sandbox Code Playgroud)
在main某个地方的开头(并确保你只做一次和一次).
虽然记住这会使它依赖于当前时间 - 如果你在同一秒内开始多个工作(或者你的时间分辨率是什么),它们将从相同的种子开始.
从C标准(C++基于这些兼容性功能):
srand函数使用该参数作为后续调用rand返回的新伪随机数序列的种子.如果随后使用相同的种子值调用srand,则应重复伪随机数序列.如果在对srand进行任何调用之前调用rand,则应该生成相同的序列,就像第一次使用种子值1调用srand时一样.
| 归档时间: |
|
| 查看次数: |
4094 次 |
| 最近记录: |