我正在尝试为卡片获取随机图片生成器。我试图使用一个数组为5个图片框生成五个不同的图片。我目前正在使用if语句,但想使用Arrays。到目前为止,这是我的代码,
Dim rndnumber As Integer
Randomize()
rndnumber = Int(Rnd() * 52) + 1
If ListBox1.Items.Contains(rndnumber) Then
rndnumber = Int(Rnd() * 52) + 1
End If
ListBox1.Items.Add(rndnumber)
If rndnumber = 1 Then
Me.playerhand1.Image = My.Resources.aceclubs
ElseIf rndnumber = 2 Then
Me.playerhand1.Image = My.Resources.acediamonds
ElseIf rndnumber = 3 Then
Me.playerhand1.Image = My.Resources.acehearts
ElseIf rndnumber = 4 Then
Me.playerhand1.Image = My.Resources.acespades
ElseIf rndnumber = 5 Then
Me.playerhand1.Image = My.Resources._2clubs
ElseIf rndnumber = 6 Then
Me.playerhand1.Image = My.Resources._2diamonds
ElseIf rndnumber = 7 Then
Me.playerhand1.Image = My.Resources._2hearts
ElseIf rndnumber = 8 Then
Me.playerhand1.Image = My.Resources._2spades
ElseIf rndnumber = 9 Then
Me.playerhand1.Image = My.Resources._3clubs
ElseIf rndnumber = 10 Then
Me.playerhand1.Image = My.Resources._3diamonds
ElseIf rndnumber = 11 Then
Me.playerhand1.Image = My.Resources._3hearts
ElseIf rndnumber = 12 Then
Me.playerhand1.Image = My.Resources._3spades
ElseIf rndnumber = 13 Then
Me.playerhand1.Image = My.Resources._4clubs
ElseIf rndnumber = 14 Then
Me.playerhand1.Image = My.Resources._4diamonds
ElseIf rndnumber = 15 Then
Me.playerhand1.Image = My.Resources._4hearts
ElseIf rndnumber = 16 Then
Me.playerhand1.Image = My.Resources._4spades
ElseIf rndnumber = 17 Then
Me.playerhand1.Image = My.Resources._5clubs
ElseIf rndnumber = 18 Then
Me.playerhand1.Image = My.Resources._5diamonds
ElseIf rndnumber = 19 Then
Me.playerhand1.Image = My.Resources._5hearts
ElseIf rndnumber = 20 Then
Me.playerhand1.Image = My.Resources._5spades
End If
End Sub
答案 0 :(得分:0)
坚持你的随机生成器,这样的事情会做:
Dim rndnumber As Integer
Randomize()
Dim rndNumberList As New List(Of Integer)
Do
rndnumber = Int(Rnd() * 52) + 1
If Not rndNumberList.Contains(rndnumber) Then
rndNumberList.Add(rndnumber)
End If
Loop Until rndNumberList.Count >= 5 'Basically you loop until you find 5 unique number
基本上你循环直到找到5个唯一数字
但我认为更好的是制作一个由数字1-52组成的列表,每次循环时,从列表中取出该元素,使其只有-1(如52到51)元素。然后重复从1到剩余卡片的过程(上一次尝试的-1)。这样,您可以确保永远不会重复两个相同的数字(您只需选择一个数字)。
备注:也许你想从0开始你的索引(从51结束),因为在VB.Net中索引从0开始