您好,我目前正在尝试使用C#中的Windows窗体应用制作猜谜游戏。我不知道该怎么做,所以我的随机数只能生成一次。例如,每次我单击我的猜测按钮(如guessButton_Click中所示)时,它都会生成一个不同的随机数。我只希望在此代码运行期间仅生成一次随机数。我该怎么做?任何帮助将不胜感激!
public partial class randomNumberForm : Form
{
Random ranNum = new Random();
int userGuess = 0;
int numberOfGuesses = 0;
public randomNumberForm()
{
InitializeComponent();
}
public void randomNumberForm_Load(object sender, EventArgs e)
{
}
public void guessButton_Click(object sender, EventArgs e)
{
int randomNumber = ranNum.Next(101) + 1;
if (int.TryParse(inputTextBox.Text, out userGuess))
{
if (userGuess < randomNumber)
{
answerLabel.Text = "Too low, try again.";
numberOfGuesses++;
guessLabel.Text = numberOfGuesses.ToString();
}
else if (userGuess > randomNumber)
{
answerLabel.Text = "Too high, try again.";
numberOfGuesses++;
guessLabel.Text = numberOfGuesses.ToString();
}
else if (userGuess == randomNumber)
{
answerLabel.Text = "You guessed the right number!";
numberOfGuesses++;
guessLabel.Text = numberOfGuesses.ToString();
}
}
else
{
MessageBox.Show("Please enter a valid integer.");
}
}
答案 0 :(得分:6)
看看您在int randomNumber = ranNum.Next(101) + 1;
行中放置的位置-这是您的按钮单击事件的第一件事,它将在每次单击按钮时运行。
在类顶部将您的randomNumber
变量声明为私有int。这将使它成为一个类变量,该变量只能从类本身内部访问。
将您的代码行randomNumber = ranNum.Next(101) + 1;
移至randomNumberForm_Load
函数中。这将在表单加载事件中填充randomNumber
变量。
答案 1 :(得分:0)
您必须具有全局变量。
请参见下面的示例
public partial class randomNumberForm : Form
{
Random ranNum = new Random();
int userGuess = 0;
int numberOfGuesses = 0;
int? randomNumber;
public randomNumberForm()
{
InitializeComponent();
}
public void randomNumberForm_Load(object sender, EventArgs e)
{
}
public void guessButton_Click(object sender, EventArgs e)
{
if (!randomNumber.HasValue) // first time run
randomNumber = ranNum.Next(101) + 1;
if (int.TryParse(inputTextBox.Text, out userGuess))
{
if (userGuess < randomNumber)
{
answerLabel.Text = "Too low, try again.";
numberOfGuesses++;
guessLabel.Text = numberOfGuesses.ToString();
}
else if (userGuess > randomNumber)
{
answerLabel.Text = "Too high, try again.";
numberOfGuesses++;
guessLabel.Text = numberOfGuesses.ToString();
}
else if (userGuess == randomNumber)
{
answerLabel.Text = "You guessed the right number!";
numberOfGuesses++;
guessLabel.Text = numberOfGuesses.ToString();
}
}
else
{
MessageBox.Show("Please enter a valid integer.");
}
}