c# - Visual Studio 上的 C# 猜数字游戏。如何阻止游戏重新启动并在每次点击时创建新的随机数?
问题描述
我知道这对你们来说很简单,很抱歉占用你们的时间,但我已经在相关帖子中搜索并尝试了所有内容。
我试图在 Visual Studio 2017 中创建简单的猜谜游戏。用户尝试通过文本框猜测 1 到 10 之间的数字,并在标签中接收输出。我让它工作(有点),但它会重新启动游戏并在每次点击时创建新的随机数。我试过添加while循环,但它只是一直持续下去,没有输出。我需要在我的代码中添加什么来阻止游戏在每次点击时重新启动并让用户继续输入猜测?
谢谢!
这是我的代码:
public partial class NumberGame : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnCalculate_Click(object sender, EventArgs e)
{
Random rand = new Random();
int value = rand.Next(0, 10);
int numGuess = 0;
int guess = Convert.ToInt32(txtGuess.Text);
if (guess > value)
{
numGuess++;
lblResult.Text = "Guess is too high, try again. ";
lblGuess.Text = "The number of guesses is " + numGuess;
}
else if (guess < value)
{
numGuess++;
lblResult.Text = "Guess is too low, try again. ";
lblGuess.Text = "The number of guesses is " + numGuess;
}
else if (guess == value)
{
numGuess++;
lblResult.Text = "You win! Good job. ";
lblGuess.Text = "The number of guesses is " + numGuess;
}
}
}
解决方案
将随机数生成部分移动到表单加载事件中,并将其分配给全局变量。
公共部分类 NumberGame : System.Web.UI.Page {
int value;
protected void Page_Load(object sender, EventArgs e)
{
Random rand = new Random();
value = rand.Next(0, 10);
}
protected void btnCalculate_Click(object sender, EventArgs e)
{
int numGuess = 0;
int guess = Convert.ToInt32(txtGuess.Text);
do{
if (guess > value)
{
numGuess++;
lblResult.Text = "Guess is too high, try again. ";
lblGuess.Text = "The number of guesses is " + numGuess;
}
else if (guess < value)
{
numGuess++;
lblResult.Text = "Guess is too low, try again. ";
lblGuess.Text = "The number of guesses is " + numGuess;
}
else if (guess == value)
{
numGuess++;
lblResult.Text = "You win! Good job. ";
lblGuess.Text = "The number of guesses is " + numGuess;
}
}while(numGuess < 3)
Page_Load();
}
}
推荐阅读
- r - 查找所有变量对之间的相交长度
- haskell - 哈斯克尔。两个列表的 INNER JOIN
- python - 在使用 groupby 函数进行分组并尝试打印数据框后,它缺少我分组的列中的值
- java - 设置纸牌游戏进入无限循环,有 2 名玩家
- python - 如何通过蓝图使用 Flask 登录
- windows-10 - Windows userprofile 文件夹根据访问方式显示不同的项目
- javascript - React-Leaflet Map 不更新
- javascript - 在 React Native 中单击图标播放音频剪辑
- rest - Tibco BW 条件流
- sql - SQL:连接表格并将每个单元格除以另一个表格中的匹配单元格?