c# - 如何在 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();
}
解决方案
您可以使用计时器来实现延迟。
如果您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();
}
推荐阅读
- java - 如何修复 Fortify Path Manipulation (Input Validation and Representation, Data Flow) 漏洞
- postgresql - 我在两列(楼层ID和票证)的弹簧启动服务中制作了复合键
- sql-server - 如何避免在 Powershell 中使用 SMO 对象的系统数据库?
- c# - 如何使用 c# 生成 UUID 版本 4
- join - 如何加入同一表中存在的列
- python - 为什么我不能从 Python 3.7.2 中的 utils 模块导入 CFEVideoConf 和 image_resize
- hibernate - 无法使用 data.sql 生成 UUID id
- android - 如何在原生应用中处理 JWT 过期机制
- go - 如何在 Go 中使用字符串类型获取字符串的十六进制值
- javascript - 我可以在 javaScript 中使用从 Node.js 抓取的内容吗?