计算尝试次数,并要求用户再次循环
本文关键字:用户 循环 计算 | 更新日期: 2023-09-27 18:13:27
我想做一款有趣的新游戏。这个游戏是关于猜一个数字。我用微软的Visual Studio制作了一张申请表。这个程序将给用户10次尝试来得到一个正确的猜测。它还会告诉你这个数字过高或过低。该程序有一个循环函数来监视尝试。如果用户猜了10次,程序将停止。问题是,显示显示未更改的尝试。例如,用户猜了5次,但程序的显示仍然显示10次尝试。如果用户使用了10次尝试,停止程序也是一样的。程序应该在尝试10次后停止,但它不工作。我找不到问题出在哪里。如果有人能帮忙的话,我将不胜感激。
public class Main : Form
int randomNumber;
int count;
private void Form1_Load(object sender, EventArgs e)
{
count = 10;
randomNumber = generateRandomNumber();
}
private void button1_Click(object sender, EventArgs e)
{
int guess = 0;
guess = Convert.ToInt32(textBox1.Text);
for (int i = 1; i <= count; i++)
{
label4.Text = "Guess Attempt: " + i;
if (guess == randomNumber)
{
label4.Text = "Your guess is correct! Game Won";
label2.Visible = false;
label3.Visible = false;
button1.Visible = false;
if (MessageBox.Show("Do you want to play again?", "Start a new game", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
{
Application.Restart();
}
else
{
Application.Exit();
}
break;
}
else
if (guess < randomNumber)
{
label2.Text = "Too low!";
}
else if (guess > randomNumber)
{
label2.Text = "Too high!";
}
else if (i == count)
{
label2.Text = "Sorry, You missed it! Game Lost";
label3.Text = "The answer is " + randomNumber;
if (MessageBox.Show("Do you want to play again?", "Start a new game", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
{
Application.Restart();
}
else
{
Application.Exit();
}
}
}
}
private int generateRandomNumber()
{
Random number = new Random();
int randomNumber = number.Next(1, 100);
return randomNumber;
}
您需要一个变量来存储与count
和randomNumber
相同级别的尝试次数,并在每次单击按钮时增加它。
public class Main : Form
int randomNumber;
int count;
int attempt;
private void Form1_Load(object sender, EventArgs e)
{
attempt = 0;
count = 10;
randomNumber = generateRandomNumber();
}
private void button1_Click(object sender, EventArgs e)
{
int guess = 0;
guess = Convert.ToInt32(textBox1.Text);
attempt++;
label4.Text = "Guess Attempt: " + attempt;
if (guess == randomNumber)
{
label4.Text = "Your guess is correct! Game Won";
label2.Visible = false;
label3.Visible = false;
button1.Visible = false;
if (MessageBox.Show("Do you want to play again?", "Start a new game", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
{
Application.Restart();
}
else
{
Application.Exit();
}
break;
}
else
if (guess < randomNumber)
{
label2.Text = "Too low!";
}
else if (guess > randomNumber)
{
label2.Text = "Too high!";
}
else if (attempt == count)
{
label2.Text = "Sorry, You missed it! Game Lost";
label3.Text = "The answer is " + randomNumber;
if (MessageBox.Show("Do you want to play again?", "Start a new game", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
{
Application.Restart();
}
else
{
Application.Exit();
}
}
}
}
private int generateRandomNumber()
{
Random number = new Random();
int randomNumber = number.Next(1, 100);
return randomNumber;
}