随机平铺中的滑动谜题帮助
本文关键字:帮助 随机 | 更新日期: 2023-09-27 18:24:30
我在创建滑动谜题时遇到问题。我正在尝试制作一种重置&打乱所有15个按钮,但问题是随机数字重复出现。
当我写bool[] usednum = new bool[array.length];
时,我得到一个错误,所以我增加了usednum数组的长度。。。。。
private void reset()
{
int[] array = { 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
int count = 0;
Random r = new Random();
bool[] usednum = new bool[50];
for (int i = 0; i < usednum.Length; i++)
usednum[i] = false;
while (count < array.Length)
{
int temp = array[r.Next(array.Length)];
if (usednum[temp] == false)
{
button1.Text = temp.ToString();
usednum[temp] = true;
count++;
}
temp = array[r.Next(array.Length)];
if (usednum[temp] == false)
{
button2.Text = temp.ToString();
usednum[temp] = true;
count++;
}
temp = array[r.Next(array.Length)];
if (usednum[temp] == false)
{
button3.Text = temp.ToString();
usednum[temp] = true;
count++;
}
temp = array[r.Next(array.Length)];
if (usednum[temp] == false)
{
button4.Text = temp.ToString();
usednum[temp] = true;
count++;
}
temp = array[r.Next(array.Length)];
if(usednum[temp] == false)
{
button5.Text = temp.ToString();
usednum[temp] = true;
count++;
}
temp = array[r.Next(array.Length)];
if (usednum[temp] == false)
{
button6.Text = temp.ToString();
usednum[temp] = true;
count++;
}
/*.
.
.
. to button 15*/
只需打乱数组:http://en.wikipedia.org/wiki/Shuffling
一个简单的混洗算法是(在伪代码中)
maxIndex = array.Length - 1
for index in 0 to maxIndex - 1
swapIndex = random number between index and maxIndex
swap (array, index, swapIndex)
不要使用静态数组,而是使用列表
var array = new int[] { 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
var unused = array.ToList();
var r = new Random();
while (unused.Count > 0)
{
int c = r.Next(unused.Count - 1);
int current = unused[c];
unused.RemoveAt(c);
//...
}