falkonidas
falkonidas

Reputation: 15

random number generator isnt working

I'm having trouble with function that generates random numbers.

I have class dice:

Public Class dice
    Private isHold As Boolean = False
    Private rnd As Random
    Private rolledDots As Integer

    Public Sub roll()

        If isHold = False Then
            rnd = New Random
            rolledDots = rnd.Next(1, 7)
        End If
    End Sub

End Class

I'm rolling dices through rollcup class:

Public Class rollCup
    Public dices As New List(Of dice)
    Sub New()
        For i = 0 To 5
            dices.Add(New dice)
        Next
    End Sub
    Public Sub rollDices()
        For Each dice In dices
            dice.roll()
        Next
    End Sub
End Class

Problem is dices arent generating random numbers. Every dice has generated same number. I can only achieve random numbers by sleep threading in loop:

Public Sub roll()
    If isHold = False Then
        rnd = New Random
        System.Threading.Thread.Sleep(50)
        rolledDots = rnd.Next(1, 7)
    End If
End Sub

or by showing each number in message box:

Public Sub roll()
    If isHold = False Then
        rnd = New Random
        rolledDots = rnd.Next(1, 7)
        MessageBox.Show(rolledDots)
    End If
End Sub

Is there any other answer to my problem ? ps. sorry for bad english.

Upvotes: 0

Views: 113

Answers (2)

dbasnett
dbasnett

Reputation: 11773

Here is your dice class with a few changes. Give it a try. The problem was that you were creating a new random in close succession which caused the numbers returned to all be the same.

Public Class dice
    Private isHold As Boolean = False
    Private Shared rnd As New Random '<<<< note Shared
    Private rolledDots As Integer

    Public Sub roll()
        If Not Me.isHold Then
            Me.rolledDots = dice.rnd.Next(1, 7)
        End If
    End Sub

End Class

See RandomWrapper

Upvotes: 1

Mike van L
Mike van L

Reputation: 375

I think your problem is that the randomgenerator is time-based, so it creates a "random" value based on the current time. And because the different dices run at practically the same time, you'll get the same random number. See: Why isn't Random() random?

Upvotes: 0

Related Questions