Jump to content

Problem with Random() in C#


Recommended Posts

Hi all, here's my first post in the programming section hope you can all help me with a problem. I've written a function to simulate the rolling of dice, but when I run it it's not very random here is the code

from CharGen.cs

private void button2_Click(object sender, System.EventArgs e)
{  
    Die die2 = new Die();
    switch (comboBox1.Text)
    {
    case "Human":
         textBox1.Text = die2.Roll(3,6).ToString();
         textBox2.Text = die2.Roll(3,6).ToString();
         textBox3.Text = die2.Roll(3,6).ToString();
         textBox4.Text = die2.Roll(3,6).ToString();
         textBox5.Text = die2.Roll(3,6).ToString();
         textBox6.Text = die2.Roll(3,6).ToString();
         break;
    }
}

and here is the code from Die.cs

using System;


namespace CharGen
{
    /// <summary>
    /// Simulates the rolling of a die, generating a random value.
    /// </summary>
    public class Die
    {
         public Die()
         {
         }

          public int Roll(int numOfDice, int typeOfDie)
          {
Random rand = new Random();
int dieTotalValue = 0;
for (int i = 1; i <= numOfDice; i++)
{
     dieTotalValue += rand.Next(1, typeOfDie);
}

return dieTotalValue;
           }
           
            public int Roll(int typeOfDie)
            {
                 Random rand = new Random();
  return rand.Next(1, typeOfDie);
             }
       }
}

When I press "Button 2" all 6 textboxes will populate with the same number, if I press the button again then all six boxes will populate with the same number again but it's a different number than the first time. I'm looking for something more random but I guess I'm too tired to see the problem

Link to comment
Share on other sites


I have resolved the problem if anyone is interested. It turns out that modern computers are so fast that the six .roll() functions were happening almost instantly so the random seed wasn't changing. I added a several millisecond delay between each .roll and now it generates a unique number each time.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...