I'm sure I'm doing something wrong; but this has been driving me crazy for a while now.
I've made a small Silverlight game (an old Galaxian clone). When the game starts ~90% of the time, a bunch of stars are randomly positioned in the game area. There are three types of stars - bigger stars more faster, smaller stars move slower.
It looks like this:
~10% of the time all of the stars appear in 'bands'
I think it's worth mentioning that even though they are in narrow bands; they aren't all in the same exact position. So it's like it is still generating a random number - just a tiny one.
To reproduce the error, I simply hit 'f5' in the browser. Nearly all the time, it works as expected. Rarely, I get the bands. Hitting 'f5' again will fix the issue.
Without posting a giant wall of code; I think this is the most relevant code. It appears in the Base class that all of my stars inherit from. It's called once, when each star is created.
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
I don't see anything wrong. GetRandom() returns a singleton Random class, and I'm depending on the GameCanvas.Height and GameCanvas.Width being valid - but again, the .Width appears to work exactly as expected.
Does anyone have a potential explanation for this behavior? Are there any gotchas to watch out for when generating random numbers? Every time I step through the code, everything is fine and the game works as expected.
If it would help I can post a link to the game.
(http://robdude.weebly.com/cci.html)
EDIT #1:
Here is the code from GetRandom()
Protected Shared Function GetRandom() As Random
If _random Is Nothing Then _random = New Random()
Return _random
End Function
EDIT #2: I really appreciate everyones thoughts/advice on this.