[英]How to make a program wait until a button is clicked?
我想知道如何讓我的程序等到按下某個按鈕。
為了說明我的問題,我制作了一個虛擬 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()”方法中按下“RollButton”?
我試圖了解事件和異步編程。 但是,作為一個初學者,我在理解這些概念上有一些困難。 另外,我不確定這些是否可以幫助解決我的問題。
為了讓您可以理解,您需要刪除Play();
在游戲窗口內。 因此你需要添加Play();
到括號內RollButton_Click(...)
的末尾。 這應該比異步編程更容易,特別是如果您只想編寫這樣一個簡單的程序。 此外,do while 循環什么也不做,只是創建一個 bool 方法來檢查骰子 1 和 2 是否具有相同的數字。 如果他們有相同的數字,你可以返回 true 結束游戲,如果沒有匹配的數字則返回 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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.