Jason Down 的建议是明智的,创建一个新GuessingGame
类并将其添加到您的项目中。我知道您担心“全局变量”(在学校里每个人都被教导永远不要使用它,除非您绝对必须这样做),但请考虑一下您的设计规范。
但是如果多次调用“Guess”按钮的事件处理程序,则该数字必须存储为 Form 的实例变量。当然,这没什么大不了的,但我认为数字应该是指导当前游戏的方法的属性,而不是 Form 的属性。
作为替代方案,将GuessingGame
类的实例存储在表单中。这不是全局变量!您自己说过,游戏的重点是跟踪猜测并在每次单击“播放”时生成新的数字进行猜测。如果您在表单中存储游戏实例然后打开另一个表单(例如帮助或关于框),则游戏实例将不可用(因此,不是全局的)。
该GuessingGame
对象将类似于:
public class GuessingGame
{
private static Random _RNG = new Random();
private bool _GameRunning;
private bool _GameWon;
private int _Number;
private int _GuessesRemaining;
public int GuessesRemaining
{
get { return _GuessesRemaining; }
}
public bool GameEnded
{
get { return !_GameRunning; }
}
public bool GameWon
{
get { return _GameWon; }
}
public GuessingGame()
{
_GameRunning = false;
_GameWon = false;
}
public void StartNewGame(int numberOfGuesses, int max)
{
if (max <= 0)
throw new ArgumentOutOfRangeException("max", "Must be > 0");
if (max == int.MaxValue)
_Number = _RNG.Next();
else
_Number = _RNG.Next(0, max + 1);
_GuessesRemaining = numberOfGuesses;
_GameRunning = true;
}
public bool MakeGuess(int guess)
{
if (_GameRunning)
{
_GuessesRemaining--;
if (_GuessesRemaining <= 0)
{
_GameRunning = false;
_GameWon = false;
return false;
}
if (guess == _Number)
{
_GameWon = true;
return true;
}
else
{
return false;
}
}
else
{
throw new Exception("The game is not running. Call StartNewGame() before making a guess.");
}
}
}
这样,所有与游戏相关的数据都封装在类中。在表单的代码隐藏中连接事件很容易:
GuessingGame game = new GuessingGame();
private void btnPlay_Click(object sender, EventArgs e)
{
int numberOfGuesses = Convert.ToInt32(txtNumberOfGuesses.Text);
int max = Convert.ToInt32(txtMax.Text);
game.StartNewGame(numberOfGuesses, max);
}
private void btnGuess_Click(object sender, EventArgs e)
{
int guess = Convert.ToInt32(txtGuess.Text);
bool correct = game.MakeGuess(guess);
if (correct)
lblWin.Visible = true;
if (game.GameEnded)
{
// disable guess button, show loss label
}
}