blah blah blah is here! blah blah » Close

up0down
link

Hello,
I have been asked to create a little game which randomizes 4 boxes into 4 set positions in a line and then can swap them around until they are back into a correct order.
I have been able to make them move around the 4 positions, i am just stuck on how to randomize them at the start.
The four left values of the buttons i want to randomize are:
74, 144, 214, 284.
Any ideas would be greatly appreciated.
Thanks
Tom

last answered 2 years ago

1 answers

up0down
link

This code should do it:
Random rand = new Random();
int[] leftValues = new int[] { 74, 144, 214, 284 };
int[] randomLeftValues = new int[4]; // all zero initially
int count = 0; // counts random values generated so far
while (count < 4)
{
int number = rand.Next(4); // gets random number from 0 to 3
if (Array.IndexOf(randomLeftValues, leftValues[number]) == -1)
{
randomLeftValues[count] = leftValues[number];
count++;
}
}

up0down
link

Cheers for the code.
I shall give it a try later tonight and let you know.
Thanks

up0down
link

looking at the code now, where do i put thereference for the four buttons that i want assorted?
what i want, is when i click a button, another 4 buttons which are in a row should change order.
the names for the four buttons are btnA, btnB, btnC and btnD.
Thanks

up0down
link

You could use a Dictionary to map the initial Left values to each button, like this:
private Dictionary<int, Button> dict;
private Random rand = new Random();
private void Form1_Load(object sender, EventArgs e)
{
dict = new Dictionary<int, Button>();
dict.Add(74, btnA);
dict.Add(144, btnB);
dict.Add(214, btnC);
dict.Add(284, btnD);
}
private void button1_Click(object sender, EventArgs e)
{
int[] leftValues = new int[] { 74, 144, 214, 284 };
int[] randomLeftValues = new int[4]; // all zero initially
int count = 0; // counts random values generated so far
while (count < 4)
{
int number = rand.Next(4); // gets random number from 0 to 3
if (Array.IndexOf(randomLeftValues, leftValues[number]) == -1)
{
randomLeftValues[count] = leftValues[number];
count++;
}
}
for(int i = 0; i < 4; i++)
{
int key = randomLeftValues[i];
Button btn = dict[key];
btn.Left = leftValues[i];
}
}

up0down
link

thats brilliant, works a treat!
Thanks a lot,
Tom

This post was imported from csharpfriends, if you have a similiar question please ask it again.

All previous members have been migrated, hope you enjoy the new platform!

Feedback