I'm trying to build a display for a die roll. What I want to do is flicker images of random faces on the die, then end with the face that shows the number rolled. After this happens, I want the function to continue and return the number of the die roll. Here's what I have
public int RollDie()
{
RollNum = dieRoll.Next(1, 7);
DispCount = 0;
Timer Time = new Timer();
Time.Interval = TimerInterval;
Time.Tick += DisplayRollHandler;
Time.Start();
System.Threading.Thread DispThread = new System.Threading.Thread(Time.Start);
DispThread.Start();
DispThread.Join();
return RollNum;
}
private void DisplayRollHandler(object sender, EventArgs evt)
{
if (DispCount < TargetDispCount)
{
Random Nums = new Random();
Display.BackgroundImage = Faces[Nums.Next(0, 6)];
DispCount++;
}
else
{
((Timer)sender).Stop();
Display.BackgroundImage = Faces[RollNum - 1];
}
}
where dieRoll
is a random object and Display
is a Panel. The image flicker works, and it does return the number of the roll consistently. Unfortunately, it doesn't wait for the display flicker to finish before continuing, which is a problem when I have automatic messages that pop up after the die is rolled.
I'm a fairly inexperienced programmer, so I'm probably missing a really basic concept. I know that if I could abstract this into a method call, I can wait for a method call to finish, but I can't figure out how to do that without using a Thread.Sleep
call and freezing the program.
Any suggestions?