jeudi 17 septembre 2015

Keeping a random number in c#

My program is set up to have the user guess an integer between 1 and 10. If the user guess to low, or high they are notified and can try again. The problem I am having is that when the user guesses incorrectly a new random number is generated. So essentially the user is never trying to guess the same number after getting it wrong. I need to make it so that when the user guesses wrong they are still trying to guess the same integer. Here is my code:

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");
        }




    }

  }
}




Aucun commentaire:

Enregistrer un commentaire