我正在制作一个拼图滑块程序,并尝试随机化图片框内的图像。我在互联网上做了一些研究,找不到我可以做的任何例子。这些是我的代码:
Random r = new Random();
PictureBox[] picBox = new PictureBox[9];
picBox[0] = new PictureBox();
picBox[1] = new PictureBox();
picBox[2] = new PictureBox();
picBox[3] = new PictureBox();
picBox[4] = new PictureBox();
picBox[5] = new PictureBox();
picBox[6] = new PictureBox();
picBox[7] = new PictureBox();
picBox[8] = new PictureBox();
我也有位图数组:
Bitmap[] pictures = new Bitmap[9];
pictures[0] = new Bitmap(@"1.1Bright.jpg");
pictures[1] = new Bitmap(@"1.2Bright.jpg");
pictures[2] = new Bitmap(@"1.3Bright.jpg");
pictures[3] = new Bitmap(@"2.1Bright.jpg");
pictures[4] = new Bitmap(@"2.2Bright.jpg");
pictures[5] = new Bitmap(@"2.3Bright.jpg");
pictures[6] = new Bitmap(@"3.1Bright.jpg");
pictures[7] = new Bitmap(@"3.2Bright.jpg");
pictures[8] = new Bitmap(@"3.3Dark.jpg");
我尝试了几种方法,但我不知道如何将随机图片[]设置到picBox []中:
for(int i=0; i<=8;i++)
{
picBox[i].Image= pictures[r.Next(0,9)];
}
这里的问题是一些图片盒,例如picBox [1]和picBox [6]是重复的图片。我如何使它们不重复?非常感谢非常感谢。
答案 0 :(得分:4)
只需填充数组并使用shuffle算法。
也许实现为扩展方法:
namespace ExtensionMethods
{
public static class Extensions
{
static Random rng = new Random();
public static void shuffle<T>(this T[] array)
{
// i is the number of items remaining to be shuffled.
for (int i = array.Length; i > 1; i--)
{
// Pick a random element to swap with the i-th element.
int j = rng.Next(i); // 0 <= j <= i-1 (0-based array)
// Swap array elements.
T tmp = array[j];
array[j] = array[i - 1];
array[i - 1] = tmp;
}
}
}
}
致电样本:
使用ExtensionMethods;
namespace ConsoleApplication
{
static class Program
{
static void Main()
{
int[] array = new int[] {1,2,3,4,5,6,7,8,9};
array.Shuffle();
}
}
}
答案 1 :(得分:4)
创建一个等于图片数组大小的bool数组
bool[] usedPictures = new bool[pictures.Length];
将此数组的值设置为false
。现在确定你的随机数,并测试是否使用了该元素,如:
int iCount = 0;
Random random = new Random();
while (iCount < pictures.Length)
{
int attempt = random.Next(0, pictures.Length);
//Ensures you will only use an available picture
if (usedPictures[attempt] == false)
{
picBox[attempt].Image= pictures[iCount];
doorUsed[attempt] = true;
iCount++;
}
}