Choosing a label at random
I'm a relative beginner with C#/Visual Studio and have recently been trying to put together a minesweeper game as practice. Does anybody know how I would choose 20 labels out of 100 on a form at random? I can't seem to think of any way.
Majid KamaliPosted Nov 13, 2010, 3:09 AM
Here's a peace of code:
//CODE START *********************************************************
Label[,] MyLabels = new Label[10, 10];
for(int i = 0; i < 10; i++
for(int j = 0; j < 10; j++)
{
MyLabels[i,j] = new Label();
MyLabels[i,j].Parent = this; // Or You can Add MyLabels[i,j] to your form controls
// Set MyLabels Location According to i, j if you want to display a 2D array
//Set MyLabels Size, Text etc.
}
int[] numbers = new int[20]; // if you want, not to have repeated numbers, you need an array.
bool repeated = false;
Random R = new Random(100);
for(int i = 0; i < 20;)
{
repeated = false;
int temp = R.Next();
for(int j = 0; j < i; j++)
if(numbers[j] == numbers[i])
repeated = true;
if(repeated == false)
{
numbers[i] = temp;
i++;
}
}
//CODE END************************************************************
I hope it helps.
Majid KamaliPosted Nov 13, 2010, 3:09 AM
Here's a peace of code:
//CODE START *********************************************************
Label[,] MyLabels = new Label[10, 10];
for(int i = 0; i < 10; i++
for(int j = 0; j < 10; j++)
{
MyLabels[i,j] = new Label();
MyLabels[i,j].Parent = this; // Or You can Add MyLabels[i,j] to your form controls
// Set MyLabels Location According to i, j if you want to display a 2D array
//Set MyLabels Size, Text etc.
}
int[] numbers = new int[20]; // if you want, not to have repeated numbers, you need an array.
bool repeated = false;
Random R = new Random(100);
for(int i = 0; i < 20;)
{
repeated = false;
int temp = R.Next();
for(int j = 0; j < i; j++)
if(numbers[j] == numbers[i])
repeated = true;
if(repeated == false)
{
numbers[i] = temp;
i++;
}
}
//CODE END** *********************************************************
I hope it helps.
theLizardPosted Nov 12, 2010, 8:21 PM