samedi 28 mars 2015

How to create a true 'Random' with Timer control?

I have a timer that clicks a button, and no matter what speed the timer is at, due to the Random having some kind of association with the clock, the outcome is predictable no matter what the speed.


I have been reading up and learned that when a new Random is initialized, it is done so with the system time, which explains why I'm getting this problem.


Here's what I have:



int win = 0;
int lose = 0;

private void button1_Click(object sender, EventArgs e)
{
Random rn = new Random();
int rnu = rn.Next(2);

if (rnu == 0)
win++;

if (rnu == 1)
lose++;

string winmsg = "Wins: " + win.ToString();
string losemsg = "Losses: " + lose.ToString();

winlbl.Text = winmsg;
loselbl.Text = losemsg;

timer1.Start();

}


And then the timer:



private void timer1_Tick(object sender, EventArgs e)
{
button1.PerformClick(); //interval 500, but always predictable.
}


My goal is to try to create a more 'Random' outcome- one that wouldn't be predictable with the timer control. However, I can't modify the speed of the timer; it must remain constant for the cycle.


I've tried stopping the timer and restarting, but even then it carries on the predictable behavior.


Does anyone know of a way to get around this or some kind of 'trick'? Or is this some C# Random limitation?





Aucun commentaire:

Enregistrer un commentaire