使用C#设计卡牌魔术游戏时遇到的问题

5

我想使用C#创建一款卡牌游戏。我在窗体上设计了图片框作为卡牌(背面)。我还为每个图片创建了一个点击方法,它会生成0到51之间的随机数,并使用该数字从图像列表中设置一张图像。

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

我的问题是有时候我会得到相同的数字(例如:两张黑桃J),我该如何避免这种情况?!(我的意思是,如果我得到了一个(5),我可能会再次得到另一个(5))


1
还是随机的!你想让它只显示一张卡片吗? - It'sNotALie.
4个回答

5

将你已经选择的数字存储在一个 HashSet<int> 中,继续选择,直到当前数字不在 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];

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


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

2
创建一个由52张卡牌组成的数组。对数组进行洗牌(例如使用快速的Fisher-Yates shuffle算法),然后在需要新的卡牌时进行迭代。
int[] cards = new int[52]; 

//fill the array with values from 0 to 51 
for(int i = 0; i < cards.Length; i++)
{
    cards[i] = i;
}

int currentCard = 0;

Shuffle(cards);

//your cards are now randomised. You can iterate over them incrementally, 
//no need for a random select
pictureBox1.Image = imageList1.Images[currentCard];
currentCard++;


public static void Shuffle<T>(T[] array)
{
    var random = _random;
    for (int i = array.Length; i > 1; i--)
    {
        // Pick random element to swap.
        int j = random.Next(i); // 0 <= j <= i-1
        // Swap.
        T tmp = array[j];
        array[j] = array[i - 1];
        array[i - 1] = tmp;
    }
}

基本上你所做的就是洗牌并每次只拿顶部的一张牌,就像在真正的游戏中一样。没有必要每次都随机选择一个索引。

1
啊,抱歉,我看错了。我以为他们想知道为什么他们连续得到相同的数字。 - keyboardP

1

我认为你可以使用一个我曾经用过的简单技巧。随机交换两个索引之间的图片50次。少于或多于50次会使随机性更加丰富。这可能与@faester的答案类似。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接