奇怪的随机数字错误在.Net

我确定我在做错事了但这已经让我疯狂了一段时间了.

我做了一个小Silverlight游戏(一个老的Galaxian克隆).当游戏开始〜90%的时候,一群星星随机位于游戏区域.有三种类型的星星 – 更大的星星越快,星星越小越慢.

看起来像这样:

〜10%的时间所有的星星出现在“乐队”

我认为值得一提的是,尽管他们在窄带中,他们并不完全相同.所以就像它仍然产生一个随机数 – 只是一个小数.

要重现错误,我只需在浏览器中点击“f5”.几乎所有的时间,它按预期工作.很少,我得到乐队.再次点击’f5’可以解决问题.

没有发布一个巨大的代码墙;我认为这是最相关的代码.它出现在Base类中,我的所有星星都继承自它.当创建每个明星时,它被调用一次.

Protected Sub SetInitialPosition()
    myElipse.Height = GetStarSize()
    myElipse.Width = GetStarSize()

    _location.X = GetRandom.Next(-1 * Settings.StarEdge,CType(GameCanvas.Width,Integer) + Settings.StarEdge)
    _location.Y = GetRandom.Next(0,CType(GameCanvas.Height,Integer))

    myElipse.Fill = New SolidColorBrush(GetStarColor)

End Sub

我没有看到任何错误. GetRandom()返回一个单例Random类,而我依赖于GameCanvas.Height和GameCanvas.Width是有效的 – 但是再次,.Width似乎按照预期的方式工作.

有人有这个行为的潜在解释吗?生成随机数时有什么问题需要注意吗?每次我通过代码,一切都很好,游戏按预期工作.

如果这将有助于我发布一个链接到游戏.
(http://robdude.weebly.com/cci.html)

编辑#1:
以下是GetRandom()的代码

Protected Shared Function GetRandom() As Random
    If _random Is Nothing Then _random = New Random()

    Return _random
End Function

编辑#2:
我非常感谢大家的想法/建议.

解决方法

我想让这个答案尽可能的通用,希望对别人有帮助.我在这里整合了其他答案(以及我的问题的实际修复),这可能有助于经历随机生成数字的奇怪行为的人.

Using Different Instances Of Random

An instance of the Random class has an associated seed. Generally speaking,you want to reuse the same instance of Random or ensure that the seeds are different. If you have 2 different Random instances created with the same seed,the first .Next will return the same result.

Thread-Safety

Random is not thread-safe.

Conditional Breakpoint

I sometimes forget that this is an option. In some cases,the act of ‘stepping through code’ will hide bugs that appear when you run-though. Setting a conditional break-point is a good way to check for this. In my case ‘CType(GameCanvas.Height,Integer) < 750’ was the condition I used.

Logging

Along those same lines,logging can be invaluable for a bug like this. I don’t know why I didn’t think of it before asking the question.

最后,由于我不明白的原因,很少有GameCanvas.Height的值设置不正确.我的理论是,当我创建/定位/大小GameCanvas时,我正在做别的事情不正确或不适当的地方.

逐行编写代码似乎无法解决问题.在我的情况下,运动场的大小是固定的;所以,而不是检查从GameCanvas控件的大小 – 我现在把它从我的设置对象.

感谢大家的团队调试.非常感谢

相关文章

如何在Silverlight4(XAML)中绑定IsEnabled属性?我试过简单的...
我正在编写我的第一个vb.net应用程序(但我也会在这里标记c#,...
ProcessFile()是在UIThread上运行还是在单独的线程上运行.如...
我从同行那里听说,对sharepoint的了解对职业生涯有益.我们不...
我正在尝试保存一个类我的类对象的集合.我收到一个错误说明:...
我需要根据Silverlight中的某些配置值设置给定控件的Style.我...