0

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.

  • You're using the same timer for each computer player. This may or may not be the right solution depending on the part of the code that actually executes the flip. (i.e. the code in `OnTimedEvent`) – Abion47 Feb 13 '19 at 20:37
  • `OnTimedEvent` does the flip. I need to wait 2 seconds (or any number of seconds) between each iteration of the foreach loop but still allow the user to click or press a key on the keyboard. The code above isn't waiting. –  Feb 13 '19 at 20:41
  • Yes, I figured that `OnTimedEvent` handles the flip. The question is exactly _how_, because that is probably where the actual problem is. – Abion47 Feb 14 '19 at 00:09

1 Answers1

0

I was able to solve this by making the function async and using await Task.Delay(2000); and not using the timer at all