Start by moving the
Random
instance out of the method, and putting it into a class level variable:
private Random rnd = new Random();
void MyMethod()
{
int dice1 = rnd.Next(1,6);
int dice2 = rnd.Next(1,6);
int dice3 = rnd.Next(1,6);
...
}
The reason for that is that
Random
is initialized with the system clock, so you don't want to create them over and over, or you will get the same sequence if you call your method too quickly. Making it class level, means it is created once, so you don't get that repetition.
Then, look at the definition of the
Next
method, and you will see that the upper bound is exclusive - the value returned will never equal it - so you need to add one in order to get a fair roll on a six sided die:
private Random myDie = new Random();
public int RollStandardDie()
{
return myDie.Next(1, 6 + 1);
}
Then call
RollStandardDie
three times to get your values, and sort them. The easiest way is like this:
private Random myDie = new Random();
public int RollStandardDie()
{
return myDie.Next(1, 6 + 1);
}
private void MyButton_Click(object sender, EventArgs ew)
{
int[] dice = new int[3];
for (int i = 0; i < dice.Length; i++)
{
dice[i] = RollStandardDie();
}
Array.Sort(dice);
Then just feed your values into your Labels or TextBoxes:
label1.Text = dice[0].ToString();
TextBox2.Text = dice[1].ToString();