首页 > 解决方案 > 如何在 C# 的纸牌游戏中决定玩家和计算机之间的轮换?

问题描述

我正在 WinForm 中使用 c# 在玩家和计算机之间构建纸牌游戏。

一开始有一个随机函数可以选择谁先玩。

如果计算机是第一个computerFunction()将执行。如果播放器是第一个有一个标签告诉播放器播放并且在播放器单击按钮之前什么都不执行,然后click_button()将执行并最终再次调用 computerFunction()。

问题是您看到它就像 computerFunction() 与 button_click 一起执行,而我看不到玩家轮到所做的更改。(我喜欢在 button_click 之后更改的标签和图像,我应该在 computerFunction() 进行自己的更改之前看到它)。

我尝试了 Thread.sleep(2000) 但它没有显示更改。此外,我将播放器函数从 button_click 复制到另一个函数,在新的 button_click 中,我首先编写了 playerFunction(),然后编写了 computerFunction()。

还是不行。

这是一个例子:

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

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

标签: c#.netvisual-studiowinforms

解决方案


您可以使用计时器来实现延迟。

如果您System.Windows.Forms.Timer在玩家的动作完成后启动 a,您在 button_click 中对表单所做的更改将被渲染,并且在间隔(此处设置为两秒)之后,将调用 ComputerFunction()。

注意:您应该防止用户在这两秒钟内再次单击该按钮。

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();
}

推荐阅读