当用户点击消息对话框"ok"时重新启动代码;按钮
本文关键字:quot 重新启动 代码 按钮 ok 用户 消息 对话框 | 更新日期: 2023-09-27 18:09:28
我正在尝试为我正在制作的一个简单的数字猜谜游戏添加代码。一旦用户猜出正确的数字,就会弹出一个消息对话框,告诉他他是赢家。该消息对话框有一个名为"ok"的按钮,当我点击它时,我被带回到表单。
相反,我希望它重新启动代码,以便生成一个新的随机数。这是可能的还是我需要手动将代码恢复到赢家代码区域内的默认状态?
下面是我的代码: private void btnEval_Click (object sender, EventArgs e)
{
// increment the counter to be displayed later
howManyClicks++;
// main decision conditions, ensures something is entered
if (txtNum.Text != "")
{
// user input number
double num = double.Parse (txtNum.Text);
if (randomNumber > num)
{
// if too low
this.BackColor = Color.Yellow;
lblMain.Text = "TOO LOW!";
lblReq.Text = "please try again";
txtNum.Clear ();
txtNum.Focus ();
}
else if (randomNumber < num)
{
// if too high
this.BackColor = Color.Red;
lblMain.Text = "TOO HIGH!";
lblReq.Text = "please try again";
txtNum.Clear ();
txtNum.Focus ();
}
else
{
// correct
this.BackColor = Color.Green;
lblMain.Text = "CORRECT!";
lblReq.Text = "well done";
MessageBox.Show ("You are right!! It took you " + howManyClicks + " guesses", "You are a WINNER!!",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
txtNum.Clear ();
txtNum.Focus ();
}
}
else
{
MessageBox.Show ("You must enter a vaild number! Please try again.", "ERROR",
MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
txtNum.Clear ();
txtNum.Focus ();
}
显然,你的"游戏状态"(howManyClicks
, randomNumber
,…)是存储在表单的实例变量中。因此,您有以下选项:
将游戏状态提取到自己的类中,并在表单中只保留对该类实例的引用:
GameState state;
当你启动或重新启动游戏时,只需将new GameState()
分配给state
并重置表单的用户界面元素。
或者,您可以关闭并重新打开表单。你的主循环可以像这样:
while (true) {
var form = new GameForm();
var result = form.ShowDialog(); // waits until the form as been closed
if (result == DialogResult.Cancel) {
break; // The user wants to stop playing
}
}
在游戏表单中,当点击OK
按钮时,将Me.DialogResult
设置为DialogResult.OK
,然后关闭表单。外部循环将自动重新打开一个新的空游戏表单。
为这段代码创建一个函数。
选择所有代码,然后右键单击它,选择第二个选项:Refactor
选择子选项:Extract a method
.
你可以为这个公共方法命名。
然后你可以从任何地方调用这个方法,(正如你提到的重新启动代码)