The code is for a number guessing game, it is suppose to generate a random number between 1-100 and the user is then suppose to guess the number. It will tell them if it is too high, or too low so they can continue to guess until they get it right (max of 10 guesses though).
I'm having problems(at least I think this is the problem) with setting and dealing with myGuess which is suppose to be the user's guess that they enter. There's no errors (anything underlined) in my code, but when I run it, no matter what number I enter it says your guess is too low in the debugger output. And I feel like it has something to do with the fact that myGuess isn't properly set the way I am thinking it is.
The class I created is suppose to be written so it can be used in any user interface, so I can't use any GUI controls, which is why I'm struggling.
Code for class I created:
namespace NumberGuessingGame
{
public class GuessingGame
{
int myGuess;
int guessesLeft = 0;
int gamesPlayed;
int gamesWon;
int gamesLost;
public GuessingGame()
{
}
public GuessingGame(int inputGuess)
{
myGuess = inputGuess;
}
public int Guess
{
get
{
return myGuess;
}
set
{
myGuess = value;
}
}
public void checkGuess()
{
Random rand = new Random();
int number = rand.Next(1, 100);
if (guessesLeft > 10)
{
Console.WriteLine("you lose!");
gamesLost++;
gamesPlayed++;
}
else if (myGuess > number)
{
Console.WriteLine("your guess is too high, try again.");
guessesLeft++;
}
else if (myGuess < number)
{
Console.WriteLine("your guess is too low, try again.");
guessesLeft++;
}
else
{
Console.WriteLine("you win!");
gamesPlayed++;
gamesWon++;
}
}
}
}
Code for the form class:
namespace NumberGuessingGame
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
int inputGuess = Convert.ToInt32(txtGuess.Text);
GuessingGame myGuess = new GuessingGame(inputGuess);
private void btnCheck_Click(object sender, EventArgs e)
{
myGuess.checkGuess();
}
}
}
The error I am getting now is
Error 1 A field initializer cannot reference the non-static field, method, or property 'NumberGuessingGame.frmMain.txtGuess'
and
Error 2 A field initializer cannot reference the non-static field, method, or property 'NumberGuessingGame.frmMain.inputGuess'
Random rand = new Random(); int number = rand.Next(1, 100);This two lines will spoil your game because every moment user will try to guess it will generate new value.Random rand = new Random(); int number = rand.Next(1, 100);in order for that not to happen?