How to use Randomize to choose from array list

66 Views Asked by At

I am trying to randomly generate, based off of the 3 array list, 3 different positions the picturebox (stickimage) will appear.

My code so far:

    Private Sub GenerateObjects()
    Dim RandomClass As New Random()         'Generate random number
    Dim Y As Integer                        'Y axis
    Dim ObstaclePos(3) As Integer           'Position where obstacle is allocated
    ObstaclePos(1) = 404
    ObstaclePos(2) = 310
    ObstaclePos(3) = 290

    Me.stickImage.Left -= 20


    If stickImage.Bounds.IntersectsWith(LeftStickBrake.Bounds) Then
        For pos = 1 To 3
            Y =                                             'This is where I am stuck
            stickImage.Location = New Point(1014, Y)


        Next pos
    End If
End Sub
1

There are 1 best solutions below

0
On

First, review your array declaration.

Dim ObstaclePos(3) As Integer
ObstaclePos(1) = 404
ObstaclePos(2) = 310
ObstaclePos(3) = 290

You should start from index 0.

Dim ObstaclePos(2) As Integer
ObstaclePos(0) = 404
ObstaclePos(1) = 310
ObstaclePos(2) = 290

Now you can generate a random index by using Random.Next(Integer).

Dim Y As Integer = ObstaclePos(RandomClass.Next(ObstaclePos.Length))