How to decide turns between player and computer in a card game in c#?

462 views Asked by At

I'm building a card game in WinForm with c# between a player and computer.

In the start there's a random function that chooses who's gonna play first.

If the computer is first the computerFunction() will execute. If the player is first there is a label that tells the player to play and nothing executes until the player clicks a button, than the click_button() will execute and in the end it calls the computerFunction() again.

The problem is that you see it like the computerFunction() executing together with the button_click and I can't see the changes that the player's turn made. (I have like labels and Images that change after the button_click and I should see it before the computerFunction() making his own changes).

I tried Thread.sleep(2000) but it didn't show the changes. Also I copied the player function from the button_click to another function and in the new button_click I wrote first the playerFunction() and then the computerFunction().

Still dosen't work.

That's an example:

computerFunction()
{
  // runs computer turn...
}

button_click()
{
  // run player turn...
  // computerFunction();
}
1

There are 1 answers

3
Oguz Ozgul On BEST ANSWER

You can use a timer to achieve the delay.

If you start a System.Windows.Forms.Timer after the player's actions are completed, the changes you do to the form in button_click will be rendered, and, after the interval (which is set here to two seconds) the ComputerFunction() will be invoked.

Note: You should prevent the user from clicking the button again during these two seconds.

private void ComputerFunction()
{
    if(computerPlayTimer != null)
    {
        computerPlayTimer.Stop();
        computerPlayTimer.Dispose();
        computerPlayTimer = null;
    }

    // Do whatever the computer does here.
    // I tested by updating a label
    label1.Text += " Computer Play ";
}

Timer computerPlayTimer; // this is a field at class level

private void button_Click(object sender, EventArgs e)
{
    // Do whatever the player does here.
    // I tested by updating a label
    label1.Text += " Player Play ";
    computerPlayTimer = new Timer() { Interval = 2000 };
    computerPlayTimer.Tick += (s, ea) => ComputerFunction();
    computerPlayTimer.Start();
}