简体   繁体   中英

How to use Randomize to choose from array list

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

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM