我有一个蜗牛课。
class snails
{
Random speedRand = new Random();
public int SnaleOffset = 9;
int speed;
public void snailChangeSpeed() { this.speed = speedRand.Next(3)+1; }
public void snailGo() { this.SnaleOffset = this.SnaleOffset + this.speed; }
}
我创建了4个蜗牛对象,当timerSnailSpeed计时器滴答时,它们会改变它们的移动速度......
private void timerSnailSpeed_Tick(object sender, EventArgs e)
{
Snail1.snailChangeSpeed();
Snail2.snailChangeSpeed();
Snail3.snailChangeSpeed();
Snail4.snailChangeSpeed();
private void timerSnailMove_Tick(object sender, EventArgs e)
{
Snail1.snailGo();
Snail2.snailGo();
Snail3.snailGo();
Snail4.snailGo();
imgSnail1.Left = Snail1.SnaleOffset;
imgSnail2.Left = Snail2.SnaleOffset;
imgSnail3.Left = Snail3.SnaleOffset;
imgSnail4.Left = Snail4.SnaleOffset;
}
然而问题是,它们的速度不会随机变化为每个蜗牛对象,而是随后所有蜗牛对象的速度。有什么想法吗?
谢谢!
答案 0 :(得分:5)
您正在创建Random
的四个实例,并且由于默认种子是基于时间的,因此它们很可能都会产生相同的随机数序列。让snails
的实例共享同一个Random
实例以避免这种情况。