【发布时间】:2013-11-21 19:58:59
【问题描述】:
我对 c# 很陌生,我正在尝试创建一个沙盒类型的游戏,我使用随机数来选择块去哪里,但我的块总是相同的,因为它总是选择相同的“随机数” .这是我的代码:
int x = 0;
public GameWindow()
{
InitializeComponent();
Blocks();
}
private void BlockThree()
{
}
private void BlockTwo()
{
x = 2;
BlockData();
}
private void BlockOne()
{
x = 1;
BlockData();
}
private async void Blocks()
{
await Task.Delay(5000);
BlockOne();
await Task.Delay(5000);
BlockTwo();
await Task.Delay(5000);
BlockThree();
}
private async void BlockData()
{
Random rand = new Random();
int num = rand.Next(1, 2);
if (num == 1)
{
if (x == 1)
{
pictureBox1.Image = Image.FromFile("C:/Program Files (x86)/SandBoxEngine/grass_side.png");
}
else
{
if (x == 2)
{
pictureBox2.Image = Image.FromFile("C:/Program Files (x86)/SandBoxEngine/grass_side.png");
}
}
}
else
{
if (num == 2)
{
if (x == 1)
{
pictureBox1.Image = Image.FromFile("C:/Program Files (x86)/SandBoxEngine/dirt.png");
}
else
{
if (x == 2)
{
pictureBox2.Image = Image.FromFile("C:/Program Files (x86)/SandBoxEngine/dirt.png");
}
}
}
}
}
}
【问题讨论】:
-
只使用 1 个
Random实例,否则你几乎总是会得到相同的随机数。 -
c# random string generator 的可能重复项
-
(基本上有很多重复的内容。)另见csharpindepth.com/Articles/Chapter12/Random.aspx
-
如果您在短时间内创建多个
Random实例,它们都将返回相同的序列。生成一个并将其存储在一个字段中。使用多线程时不要忘记使用适当的锁定,Random不是线程安全的。