Question Help with very easy coding for a randomizer

Ojlister

New member
Joined
Aug 4, 2015
Messages
2
Programming Experience
Beginner
Hello, so this is my first post so sorry if I muck things up a bit :). I am working on a random number generator to generate some stats for an enemy character. I can get a random number to generate however it is the same for each stat. E.g. 57 for EnemyDamage, EnemyDefence, and EnemyAgility instead of different numbers for each. Heres my code:

Private Sub Fighting_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Randomizing Enemy Stats
Dim RndEnemyDamage As Random
Dim RndEnemyDefence As Random
Dim RndEnemyAgility As Random
Dim EnemyDamage As Integer
Dim EnemyDefence As Integer
Dim EnemyAgility As Integer
RndEnemyDamage = New Random
RndEnemyDefence = New Random
RndEnemyAgility = New Random


EnemyDamage = RndEnemyDamage.Next(50, 100)
EnemyDefence = RndEnemyDefence.Next(50, 100)
EnemyAgility = RndEnemyAgility.Next(50, 100)


' Displaying the stats in labels
Label11.Text = EnemyDamage.ToString
Label10.Text = EnemyDefence.ToString
Label9.Text = EnemyAgility.ToString


End Sub

This is probably quite an obvious one, but I'm not the best when it comes to coding.
Thanks,
OJ
 

JohnH

VB.NET Forum Moderator
Staff member
Joined
Dec 17, 2005
Messages
15,553
Location
Norway
Programming Experience
10+
You only need one instance of the Random class, like this:
    

    Private Sub Fighting_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim rnd As New Random
        ' Displaying the stats in labels
        LabelEnemyDamage.Text = rnd.Next(50, 100).ToString
        LabelEnemyDefence.Text = rnd.Next(50, 100).ToString
        LabelEnemyAgility.Text = rnd.Next(50, 100).ToString
    End Sub

Also notice naming the labels makes the code much more readable.

Also, if you need to generate more random values in other methods I recommend you declare it outside the local method, like this:
    Private rnd As New Random

    Private Sub Fighting_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ' ....
 
Top Bottom