Reputation: 63
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 ?
Upvotes: 0
Views: 92
Reputation: 19486
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
}
}
}
}
Upvotes: 2