我正在尝试制作一款有趣的新游戏。游戏是猜一个数字。我使用Microsoft Visual Studio制作申请表。该程序将使用户10尝试获得正确的猜测。它还会告诉数字太高或太低。该程序具有循环功能来监控尝试。如果用户猜了10次,程序将停止。问题是显示屏显示未更改的尝试。例如,用户猜测了五次,但节目的显示仍显示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;
}
答案 0 :(得分:0)
您需要一个变量来存储与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;
}