2013-01-04 142 views
2

我正在使用图片框显示图像,并在一秒钟间隔内对其进行计时。我试图避免连续两次显示相同的图像,并使用数组列表来执行此操作,以避免接下来的相同随机图像。试图避免两次显示相同的图像

这就是我所做的。没有像我期望的那么好,最终得到一个例外。 我该如何改进以避免连续两次显示相同的图像?

Random random = new Random(); 
     ArrayList imagesList = new ArrayList(); 
     Image[] images = { imageOne, imageTwo, imageThree, imageFour, imageFive, imageSix, imageSeven }; 

     do 
     { 
      try 
      { 
       for (int i = 0; i < images.Length; i++) 
       { 

        imagesList.Add(images[random.Next(0, 7)]); 

        while (imagesList.Contains(images[i])) 
        { 
         imagesList.Clear(); 
         imagesList.Add(images[random.Next(0, 7)]);  

        } 
        picImage.Image = (Image)imagesList[0]; 

       } 

       Thread.Sleep(1000); 
      } 
      catch (IndexOutOfRangeException ind) 
      { 
       MessageBox.Show(ind.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); 
      } 
      catch (Exception exe) 
      { 
       MessageBox.Show(exe.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); 
      } 


     } while (true); 
    } 
+1

不是答案,而只是一个提示:我不会在代码中使用Thread.Sleep。你会阻止你的用户界面,刷新图片,并再次阻止。在这种情况下,我会使用计时器来使用户界面可用:) – 2pietjuh2

+0

要改进代码 - 删除“睡眠”,以改善问题格式样本,减少空间并提供有关您所面临错误的信息。也许可以指定“一个,两个,一个,两个,一个,两个,一个”是否可以接受,或者你希望所有的值都存在,但是洗牌(洗牌可能是这个问题的好搜索术语)。 –

+0

我猜他的问题是随机可以显示2倍相同的值。你可以做一个数组shuffel?然后你可以一次遍历所有图像。没有随机的。这是你想要的吗? – Laurence

回答

2

只需重新排序的图像:

Image[] randomOrder = images.OrderBy(i => Guid.NewGuid()).ToArray(); 

,并通过该数组迭代。

您还需要使用计时器来更改图像,因为您当前正在阻止UI线程。 System.Windows.Forms.Timer将是适当的。您的计时器Tick事件处理会是这个样子:

private int index = 0; 

private void Timer_Tick(Object sender, EventArgs args) 
{ 
    picImage.Image = randomOrder[index % randomOrder.Length]; 
    index++; 
} 

这个TimerMSDN示例代码也是有帮助的。请注意,框架中有几个Timer类,这里可能是最好的。

5

你可以做一个洗牌而不是随机数。然后,您无需每次检查图像是否已被使用。看看这里,看看你可以如何洗牌阵列:http://www.dotnetperls.com/shuffle。现在你可以遍历数组,它现在是随机的,你不会得到重复。

我想你使用睡眠来避免每次都得到相同的随机值?你现在可以删除它。除此之外,它会阻止用户界面。