使用C#设计卡片技巧游戏的一个问题

Joh*_*ohn 5 c#

我想用C#创建一个卡片技巧游戏.我在表单上设计了Picture Boxes作为卡片(背面).我还为每个创建0到51之间的随机数的图片创建了一个Click方法,并使用该数字从ImageList设置图像.

        Random random = new Random();
        int i = random.Next(0, 51);
        pictureBox1.Image = imageList1.Images[i];
Run Code Online (Sandbox Code Playgroud)

我的问题是,有时我会得到相同的数字(例如:两个黑桃杰克),我该如何防止这种情况?!(我的意思是,例如,如果我得到(5),我可能得到另一个(5))

fae*_*ter 5

将您已选择的数字存储在a中HashSet<int>并继续选择,直到当前的nunber不在HashSet:

// private HashSet<int> seen = new HashSet<int>();
// private Random random = new Random(); 

if (seen.Count == imageList1.Images.Count)
{
    // no cards left...
}

int card = random.Next(0, imageList1.Images.Count);
while (!seen.Add(card))
{
    card = random.Next(0, imageList1.Images.Count);
}

pictureBox1.Image = imageList1.Images[card];
Run Code Online (Sandbox Code Playgroud)

或者,如果需要选择多个数字,可以使用序列号填充数组,并将每个索引中的数字与另一个随机索引中的数字交换.然后从随机数组中取出前N个需要的项目.


Mik*_*cup 5

如果您想确保没有重复图像,可以列出剩余的卡片,并每次删除显示的卡片.

Random random = new Random();    
List<int> remainingCards = new List<int>();

public void SetUp()
{
    for(int i = 0; i < 52; i++)
        remainingCards.Add(i);
}

public void SetRandomImage()
{
   int i = random.Next(0, remainingCards.Count);
   pictureBox1.Image = imageList1.Images[remainingCards[i]];
   remainingCards.RemoveAt(i);
} 
Run Code Online (Sandbox Code Playgroud)