Search code examples
vb.netrandomconsole-applicationbasic

Visual Basic Console - Integer that would randomly generate every times its used


What i'm basicly looking to do here is create somewhat of a dice that would be rolled everytime I ask it to be used in an equation. For example if I create a d10 and use the following code:

Dim PlayerStr As Integer
PlayerStr = 2
Dim PlayerHit As Integer    
PlayerHit = d10 + PlayerStr

Is there are way for me to use the d10 again later in the code for example for something like this Enemyhit = d10 + enemystr and have the d10 be "rolled" both times? I've tried doing it this way

Module Module1

    Public RNG As New Random
    Public d10 As Integer
    d10 = RNG.next(1, 11)
Sub Main ()
...
End Sub

End Module

But as far as I understand this it would roll the d10 once the program starts and then use that value every time it would be told to use the d10 or am I mistaken?


Solution

  • Instead of re-using the Integer variable, re-use a function that returns a random Integer:

    Private m_rng As New Random()
    
    Private Function Roll()
    
        Dim d10 As Integer
        d10 = m_rng.next(1, 11)
    
        Return d10
    
    End Function
    

    Then use it like this:

    PlayerHit = Roll() + PlayerStr
    

    And:

    Enemyhit = Roll() + enemystr