首页 > 解决方案 > 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;

            }

    }
}

标签: c#webforms

解决方案


将随机数生成部分移动到表单加载事件中,并将其分配给全局变量。

公共部分类 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();
}

}


推荐阅读