微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

奇怪的随机数字错误在.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控件的大小 – 我现在把它从我的设置对象.

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐