我正在尝试生成随机数 0-49。只要随机数不是 0,我就想在网格中绘制链接。每次我得到一个 0,它后面跟着另外十个 0(给或拿)。在我的研究中,他们说如果我继续创建我的 Random 的新实例,这将是问题所在,但我没有这样做。我的代码如下:
//Class begins
namespace Mascape
{
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Wall[, ,] walls = new Wall[2, 15, 10];
int mapWidth=15;
int mapHeight=10;
Random rand = new Random(); //Outside of any methods or loops.
int mapFullness;
//下面是我的Initialize()方法
//i is horizontal vs. vertical link
//j is the x position of the link
//k is the y position of the link
mapFullness = 50;
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < mapWidth; ++j)
{
for (int k = 0; k < mapHeight; ++k)
{
if (!(rand.Next(50) == 0))
{
walls[i, j, k].active = true; //Links are drawn if active
}
}
}
}
我正在尝试绘制一个带有随机缺失链接的网格。目标是让它们分散开来,出现大约五分之一。这是实际结果:
知道为什么缺乏随机性吗?如果您想了解更多信息,请告诉我。
最佳答案
应该还有更多。请参阅从您的代码复制的以下代码按预期生成随机数。
Random rand = new Random();
int mapWidth = 5;
int mapHeight = 10;
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < mapWidth; ++j)
{
for (int k = 0; k < mapHeight; ++k)
{
Console.WriteLine(rand.Next(50));
}
}
}
关于c# - map 生成器缺乏随机性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21418980/