随机和种子,生成相同的值吗?
我正在开发一个小型 XNA 游戏,
for (int birdCount = 0; birdCount < 20; birdCount++)
{
Bird bird = new Bird();
bird.AddSpriteSheet(bird.CurrentState, birdSheet);
BIRDS.Add(bird);
}
上面的代码在 Load 函数中运行,BIRDS 是保存所有鸟的列表。
小鸟构造函数随机定制小鸟。如果我逐个断点地运行代码,随机函数会生成不同的值,但如果我不停止代码并让程序运行,所有随机值都会变得相同,这样所有的鸟就会变得相同。
我该如何解决这个问题?
随机和种子的代码:
private void randomize()
{
Random seedRandom = new Random();
Random random = new Random(seedRandom.Next(100));
Random random2 = new Random(seedRandom.Next(150));
this.CurrentFrame = random.Next(0, this.textures[CurrentState].TotalFrameNumber - 1);
float scaleFactor = (float)random2.Next(50, 150) / 100;
this.Scale = new Vector2(scaleFactor, scaleFactor);
// more codes ...
this.Speed = new Vector2(2f * Scale.X, 0);
this.Acceleration = Vector2.Zero;
}
I'm developing a small XNA GAME,
for (int birdCount = 0; birdCount < 20; birdCount++)
{
Bird bird = new Bird();
bird.AddSpriteSheet(bird.CurrentState, birdSheet);
BIRDS.Add(bird);
}
The code above runs at Load function, BIRDS is the List where all Bird's are held.
The bird constructor customize the bird randomly. If I run the code breakPoint by breakPoint the random function generates different values, but if i do not stop the code and leave program running all random values become same so that all of birds become same.
How can i solve this problem ?
the code for random and seeds:
private void randomize()
{
Random seedRandom = new Random();
Random random = new Random(seedRandom.Next(100));
Random random2 = new Random(seedRandom.Next(150));
this.CurrentFrame = random.Next(0, this.textures[CurrentState].TotalFrameNumber - 1);
float scaleFactor = (float)random2.Next(50, 150) / 100;
this.Scale = new Vector2(scaleFactor, scaleFactor);
// more codes ...
this.Speed = new Vector2(2f * Scale.X, 0);
this.Acceleration = Vector2.Zero;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您很可能在代码中重复创建一个新的
Random
对象 - 相反,创建 Random 对象一次(即通过使其静态或传递它作为参数)由于
Random
默认构造函数使用当前时间作为初始种子,并且具有相同种子的Random
的所有实例都会创建相同的数字序列,从而创建新的随机
对象以快速顺序可能产生完全相同的数字序列。这听起来像你所看到的。Chances are you are repeatedly creating a new
Random
object in your code - instead create theRandom
object once only (i.e. by making it static or passing it as a parameter)Since the
Random
default constructor uses the current time as initial seed and all instances ofRandom
with the same seed create the same sequence of numbers creating newRandom
objects in fast order might produce the same exact sequence of numbers. This sounds like what you are seeing.