I'm creating a card game, Slap Jack, that has 1 user and 3 commputer "players". When the user clicks a button to flip a card, the computers will go one by one and flip a card as well.
I'm struggling with how to get the computers to run with a delay in between their executions. I have a function right now that simulates the computers flipping, but the delay is only working for the first flip, as the other two are immediately after that. This is the code I have working so far:
foreach (var player in Players.Where(a => a.IsComputer()))
{
_player = player;
_dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
_dispatcherTimer.Tick += new EventHandler(OnTimedEvent);
_dispatcherTimer.Interval = new TimeSpan(0, 0, 2);
_dispatcherTimer.Start();
}
Where OntimedEvent is the function that handles the computer flipping as well as stopping the dispatcherTimer (which is a global field) and _player is the active player. Like I said, this pauses for the first iteration of the foreach loop, but doesn't pause for the second or third. I've tried using the System.Timer class as well but that was creating a second thread and not working as I needed it to. Is there something I'm doing wrong here or is there a better way to do it?
EDIT: I think I realize how the DispatcherTimer is wrong, as it executes the remaining code below the foreach loop and then waits for the timer to elapse.
I was able to solve this by making the function async and using await Task.Delay(2000);
and not using the timer at all