在c#中保留一个随机数

Bri*_*per -2 c# random winforms

我的程序设置为让用户猜测1到10之间的整数.如果用户猜测太低或高,他们会收到通知并可以再试一次.

我遇到的问题是,当用户猜错时,会生成一个新的随机数.因此,基本上用户在错误之后永远不会尝试猜测相同的数字.

我需要这样做,以便当用户猜错时,他们仍在尝试猜测相同的值.

这是我的代码:

namespace IntegerGame
{
    public partial class guessGame : Form
    {
        int num1;
        int num2;

        public guessGame()
        {
            InitializeComponent();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
        }

        private void guessButton_Click(object sender, EventArgs e)
        {
            Random rnd1 = new Random();
            num1 = rnd1.Next(1, 10);

            if (int.TryParse(textBox1.Text, out num2))
            {
                if (num2 < 0 || num2 > 10)
                {
                    textBox1.Clear();
                    MessageBox.Show("Please enter a number between 1 and 10");
                }
                else
                {
                    if (num2 > num1)
                    {
                        textBox1.Clear();
                        MessageBox.Show("You guessed to high, please try again");
                    }

                    else if (num2 < num1)
                    {
                        textBox1.Clear();
                        MessageBox.Show("You guessed to low, please try again");
                    }

                    else if (num2 == num1)
                    {
                        textBox1.Clear();
                        MessageBox.Show("You guessed " + num2 + ", which was the right number!!");
                    }
                }

            }
            else
            {
                textBox1.Clear();
                MessageBox.Show("This is not a valid integer, please enter a valid integer");
            }
       }
    }
}
Run Code Online (Sandbox Code Playgroud)

Óla*_*ron 7

生成随机数作为guessGame的成员(或在构造函数中,在InitializeComponent之后),而不是每当用户按下按钮时

public partial class guessGame : Form
{
    Random rnd1 = new Random();
    int num1 = rnd1.Next(1, 10);
    int num2;
    ...
Run Code Online (Sandbox Code Playgroud)