Upon playing with the graphics/random class - I have discovered something odd.

Private Sub Me_Load(sender As Object, e As EventArgs) Handles Me.Load
    For i = 0 To 5000
        DrawColor(GimmiRectangle)
    Next
End Sub

Private Sub DrawColor(ByVal rNew As Rectangle)
    Try
        Dim g As Graphics = Me.CreateGraphics

        g.DrawRectangle(New Pen(Color.FromArgb(New Random().Next(255), New Random().Next(255), New Random().Next(255))), rNew)
    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try
End Sub

Private Function GimmiRectangle() As Rectangle
    Try
        Dim rect As New Rectangle(New Random().Next(1000), New Random().Next(1000), New Random().Next(1000), New Random().Next(1000))
        Return rect
    Catch ex As Exception
        MsgBox(ex.ToString)
        Return New Rectangle(0, 0, 0, 0)
    End Try
End Function

This code will generate random sized/location rectangles and draw them to the screen. (place on a blank form)

The Random class seems to be not so random. For the most part - the rectangles appear to grow to the bottom right of the screen (with fairly few rendering in the margins.)

Has anyone else noticed this odd behavior with Random?

Recommended Answers

All 2 Replies

Random is a pseudoRandom generator. You are creating a new instance each time. Without checking the docs, I believe it seeds based on system time. Therefore your seed value on differs only a bit on each creation.

Try this:

Private rnd As New Random
Private Sub Me_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Shown

   DrawColor(New Rectangle(50, 50, 100, 100))
    For i As Int32 = 0 To 20
        DrawColor(GimmiRectangle)
    Next
End Sub

Private Sub DrawColor(ByVal rNew As Rectangle)
    Try
        Dim g As Graphics = Me.CreateGraphics

        g.DrawRectangle(New Pen(Color.FromArgb(rnd.Next(255), rnd.Next(255), rnd.Next(255))), rNew)
        g.Dispose()

    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try
End Sub

Private Function GimmiRectangle() As Rectangle
    Try
        Dim rect As New Rectangle(rnd.Next(1000), rnd.Next(1000), rnd.Next(1000), rnd.Next(1000))
        Return rect
    Catch ex As Exception
        MsgBox(ex.ToString)
        Return New Rectangle(0, 0, 0, 0)
    End Try
End Function

I figured that was the case. Just didn't know how it generated it's "random" number.

More of an oddity than a problem. :)

Thanks TNT!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.