对于我的代码,这是一个数字猜谜游戏。他们在输了之前得到了10个猜测,并告诉他们是否太低,太高等等。在我的输出中,当我告诉他们是否太高或太低时,我还想显示多少猜测他们离开了。但目前它告诉他们每次都有9次猜测,我不知道为什么。
该计划的其余部分有效。因此,经过10次猜测后,它会告诉他们他们输了,只是每次猜测都会说他们还有9次猜测。
namespace NumberGuessingGame
{
public class GuessingGame
{
int myGuess = 0;
int guessesLeft = 10;
int gamesPlayed = 0;
int gamesWon = 0;
int gamesLost = 0;
Random rand;
int number = 0;
public GuessingGame()
{
rand = new Random();
number = rand.Next(1, 100);
}
public void ResetGame()
{
number = rand.Next(1, 100);
guessesLeft = 10;
}
public int CheckGuess(int newGuess)
{
myGuess = newGuess;
if (guessesLeft < 1)
{
gamesLost++;
gamesPlayed++;
ResetGame();
return 2;
}
else if (myGuess > number)
{
guessesLeft--;
return 1;
}
else if (myGuess < number)
{
guessesLeft--;
return -1;
}
else
{
gamesPlayed++;
gamesWon++;
ResetGame();
return 0;
}
}
}
}
表单类的代码
namespace NumberGuessingGame
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
GuessingGame myGuess = new GuessingGame();
private void btnCheck_Click(object sender, EventArgs e)
{
int inputGuess = Convert.ToInt32(txtGuess.Text);
int result = myGuess.CheckGuess(inputGuess);
int guessesLeft = 10;
if(result == 2)
{
MessageBox.Show("You ran out of guesses and lost!");
}
else if(result == 1)
{
guessesLeft--;
MessageBox.Show("Your guess was too high, try again!" + "\n You have " + guessesLeft + " guesses left");
}
else if(result == -1)
{
guessesLeft--;
MessageBox.Show("Your guess was too low, try again!" + "\n You have " + guessesLeft + " guesses left");
}
else if(result == 0)
{
MessageBox.Show("You won!");
}
}
}
}
答案 0 :(得分:2)
每次单击该按钮时,都会将guessesLeft设置为10,这会导致出现问题。如果你将guessesLeft设为私有字段,它将被修复。
像这样:
public partial class frmMain : Form
{
private int guessesLeft = 10;
etc.
答案 1 :(得分:1)
您有2个单独的guessesLeft
个变量 - 一个位于btnCheck_Click
事件方法中,另一个位于GuessingGame
类中。每次单击该按钮时,它都会初始化一个新的guessesLeft
并将其设置为10
,将其递减,然后该变量超出范围。您应该只有一个包含该信息的变量,并且最佳位置将作为公共财产存在于您的guessingGame
类中:
public class GuessingGame
{
public int GuessesLeft { get; private set; }
}
并在点击事件中使用它:
MessageBox.Show("Your guess was too high, try again!" + "\n You have "
+ myGuess.GuessesLeft + " guesses left");
答案 2 :(得分:1)
private void btnCheck_Click(object sender, EventArgs e)
{
int guessesLeft = 10;
此guessesLeft
是btnCheck_Click()
堆栈上的局部变量。它在函数返回时被销毁,并在每次按下按钮并重新调用函数时重新创建并重新初始化为10。
您需要公开guessesLeft
课程中的GuessingGame
。最好的方法是通过只读属性:
public class GuessingGame
{
// ...
public int GuessesRemaining
{
get { return guessesRemaining; }
}
答案 3 :(得分:0)
每次单击按钮时,您都会将guessesLeft变量重新初始化为10。您想要从您创建的名为myGuess的GuessingGame对象中查询变量。