vendredi 22 décembre 2017

C# Randomly generated values are not really random

I am making a simple game in C# and using Random class to generate a random number every 2 seconds, but it gives numbers that I can guess in advance because it increments by a certain number each time.

private int RandomNumber;

//This Timer function runs every 2 seconds
private void TmrGenerateRandomNum(object sender, EventArgs e)
{
    Random r = new Random();
    RandomNumber = r.Next(50, 200); //Trying to get random values between 50 and 200
    Label1.Text = RandomNumber.ToString();
}

This is literally the only code I have, and I am displaying the value each time through Label1. The problem is, for example, if I first get 52, the next "randomly"-generated value is 71 or 72, and the next one is 91 or 92, and the next one is 111 or 112. As you can see, it is incrementing by 20ish. Then it suddenly gets a real random value again like, say, 163. But then the next generated number is 183, again incremented by 20. Since 183+20 exceeds the range, it gets a real random value again, say 83. But the next number generated is again 103, or 104, and then 123 or 124...

This is not "Random" because you can tell around what number the next one is going to be... and this is driving me crazy. Do you know why it does this, and is there a fix for this?




Aucun commentaire:

Enregistrer un commentaire