0

I'm learning the Windows Application Form in Visual Studio, I'm making a number guessing game where the program generates a random number. I put the random number generator inside the Button_Click method, I want the number to say the same when the program start but it change every time I click the button.

public partial class myWindow : Form
{


    public myWindow()
    {
        InitializeComponent();
    }

    private void guessButton_Click(object sender, EventArgs e)
    {

            Random random = new Random();
            int roll = random.Next(0, 99);

Where should I declare or put the random number generator and variable so it doesn't change ?

6
  • Try Random random = new Random(1); Commented Jan 27, 2016 at 22:58
  • @YacoubMassad Good for a guessing game you can run one time. :) Commented Jan 27, 2016 at 22:58
  • Should the second button click always show the same number? And the third...? Commented Jan 27, 2016 at 23:00
  • Can you elaborate on this "I want the number to say the same when the program start but it change every time I click the button"? Commented Jan 27, 2016 at 23:12
  • @YacoubMassad - I think he wants the program to generate a random number when the game starts, but to only generate a new one after the user has successfully guessed the current number - not every time the user guesses. Commented Jan 28, 2016 at 0:46

1 Answer 1

2

Make it a class member:

public partial class myWindow : Form
{
    private int _roll;
    private int _numGuesses;

    public Window()
    {
        InitializeComponent();

        Random random = new Random();
        _roll = random.Next(0, 99);
    }

    private void guessButton_Click(object sender, EventArgs e)
    {
        bool isGuessCorrect = // Set this however you need to

        if (isGuessCorrect)
        {
            // They got it right!
        }
        else
        {
            _numGuesses++;
            if (_numGuesses > 9)
            {
                // Tell them they failed
            }
            else
            {
                // Tell them they're wrong, but have 10 - _numGuesses guesses left
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

I hope I don't bother you much, but i want the player to have 10 chances to guess the right number. I know i have to put a for loop, but again i don't know what to put the loop.
You'll need to track the number of guess also. I'll update my answer to show what I mean.
Thank you for your help I really appreciate it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.