1

In Visual Basic, I'm trying to roll two dice. I'm always getting die1 and die2 being the same random Integer from 1 to 6. Why aren't die1 and die2 each random and showing as different random values??? In the RollD6() function, n is of local scope within RollD6(), right?

Public Class frmCrapsWin
    Dim pot As Decimal = 0D
    Dim point, result As Integer
    Dim wager As Decimal = 0D
    Dim points(99) As Integer
    Dim wagerCoefficient(99) As Decimal

    Function RollD6() As Integer
        Dim randomNum As New Random
        Dim n As Integer
        n = randomNum.Next(1, 7)  ' random number (1,6)
        Return n
    End Function

    Private Sub btnRoll_Click(sender As Object, e As EventArgs) Handles btnRoll.Click
        Dim die1 As Integer
        Dim die2 As Integer
        die1 = RollD6()
        die2 = RollD6()
        lstOutput.Items.Add("die 1: " & die1 & "    die 2: " & die2 & "     Result: " & (die1 + die2))
        lstOutput.Items.Add("die 1: " & die1)
        lstOutput.Items.Add("die 2: " & die2)

    End Sub
End Class

  • The rule for successful random numbers is only one instance of `Random` per thread. Try this: ` Private randomNum As New Random`. – Enigmativity Aug 30 '20 at 23:46
  • I solved the problem by using the Rnd() function: ``` Function RollD6() As UInteger RollD6 = (Math.Floor(6 * Rnd())) + 1 Return RollD6 End Function ``` When the form loads, I use the Randomize() method to make sure I don't always get the same sequence of random numbers from run to run. – Paolo Barone Aug 31 '20 at 05:07
  • That's a bad RNG. You should use `Random` at least. – Enigmativity Aug 31 '20 at 06:01

0 Answers0