2013-05-19 56 views
5

我想用C#创建一个卡技巧游戏。我在表单上设计了图片框作为背景(背面)。我还为每个图片创建了一个Click方法,该方法创建一个介于0和51之间的随机数字,并使用该数字从ImageList中设置图像。使用C#设计一个卡技巧游戏的问题#

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

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

+1

它仍然是随机的!你想做到这一点,以便你只能显示一次卡? –

回答

5

商店,你在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]; 

或者,如果需要选择多个号码,您可以填写一个数组序列号并将每个索引中的数字与另一个随机索引中的数字进行交换。然后从随机数组中取出最需要的N个项目。

+0

非常感谢。代码与我一起工作。 – John

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

+1,这是最“喜欢”一款纸牌游戏。 – user7116

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

我想你可能会使用我曾经使用过的一个简单的技巧。在2个随机索引之间交换图像50次。少或多会给你一个随机的更多变化。这可能与@ faester的答案类似。

+0

??????????????? –