如何使用Randomize从数组列表中进行选择

时间:2014-11-12 12:42:51

标签: .net arrays vb.net random basic

我试图根据3个阵列列表随机生成3个不同的位置,图片框(stickimage)将出现。

到目前为止我的代码:

    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 个答案:

答案 0 :(得分:1)

首先,检查你的数组声明。

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

您应该从索引0开始。

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

现在,您可以使用Random.Next(Integer)生成随机索引。

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