如何让程序等待直到按钮被点击?



我想知道如何让我的程序等待,直到某个按钮被按下。

为了说明我的问题,我制作了一个虚拟的WPF游戏,用户可以投掷两个骰子,只要他没有得到两次。游戏的目标是掷出最高的点数。

我有以下的"骰子"类:

class Dice
{
TextBlock diceTextBlock;
const int minNumber = 1;
const int maxNumber = 6;
int number;
public int Number
{
get { return number; }
set
{
number = value;
diceTextBlock.Text = number.ToString();
}
}
public Dice(TextBlock diceTextBlock)
{
this.diceTextBlock = diceTextBlock;
Number = minNumber;
}
public void Roll()
{
Number = new Random().Next(minNumber, maxNumber + 1);
}
}

我也有以下'GameWindow'类:

public partial class GameWindow : Window
{
Dice dice1;
Dice dice2;
int rollCount;
public GameWindow()
{
InitializeComponent();
dice1 = new Dice(Dice1TextBlock);
dice2 = new Dice(Dice2TextBlock);
rollCount = 0;
Play();
}
private void RollButton_Click(object sender, RoutedEventArgs e)
{
dice1.Roll();
dice2.Roll();
rollCount++;
}
private void Play()
{
do
{
//  Wait for the user to press the 'RollButton'
}
while (dice1.Number != dice2.Number);
}
}

我如何让我的程序等待用户按下'滚动按钮'在'Play()'方法?

我试着学习事件和异步编程。然而,作为一个初学者,我有一些困难来理解这些概念。而且,我不确定这些是否能帮助解决我的问题。

为了让你更容易理解,你需要删除GameWindow中的Play();。因此,您需要将Play();添加到括号内RollButton_Click(...)的末尾。这应该比异步编程更容易,特别是如果你只是想做这样一个简单的程序。同样,do while循环什么也不做,只是创建一个bool方法来检查骰子1和2是否有相同的数字。如果他们有相同的数字,你可以返回真结束游戏,如果没有匹配的数字false。在RollButton_Click(...)方法中,检查两个数字是否匹配。如果是,则显示两个数字匹配的消息以及尝试了多少次

您可以使用SemaphoreSlim来异步等待:

public partial class GameWindow : Window, IDisposable
{
Dice dice1;
Dice dice2;
int rollCount;
SemaphoreSlim semaphore = new SemaphoreSlim(0, 1);
public GameWindow()
{
InitializeComponent();
dice1 = new Dice(Dice1TextBlock);
dice2 = new Dice(Dice2TextBlock);
rollCount = 0;
Loaded += async (s,e) => await PlayAsync();
}
private void RollButton_Click(object sender, RoutedEventArgs e)
{
dice1.Roll();
dice2.Roll();
rollCount++;
semaphore.Release();
}
private async Task PlayAsync()
{
//  Wait for the user to press the 'RollButton'
do
{
await semaphore.WaitAsync();
}
while (dice1.Number != dice2.Number);
MessageBox.Show("Yes!");
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
semaphore.Dispose();
}
public void Dispose()
{
semaphore.Dispose();
}
}

最新更新